perl - 在 Perl 中访问字符串中的单个字符时,是 substr 还是拆分为数组更快?

标签 perl string performance character

我正在编写一个 Perl 脚本,我需要在其中循环字符串的每个字符。有很多字符串,每一个都有 100 个字符长(它们是很短的 DNA 序列,以防你想知道)。

那么,使用 substr 是否更快?一次提取每个字符,还是更快 split将字符串放入数组中,然后遍历数组?

在等待答案的同时,我想我会阅读有关如何在 Perl 中进行基准测试的内容。

最佳答案

这实际上取决于您对数据的处理方式——但是,嘿,您的最后一个问题是正确的!不要猜测,基准测试。

Perl 提供了 Benchmark正是这种事情的模块,并且使用它真的非常简单。这是一个开始使用的小示例代码:

#!/usr/bin/perl
use strict;
use warnings;
use Benchmark qw(cmpthese);

my $dna;
$dna .= [qw(G A T C)]->[rand 4] for 1 .. 100;

sub frequency_substr {
  my $length = length $dna;
  my %hist;

  for my $pos (0 .. $length) {
    $hist{$pos}{substr $dna, $pos, 1} ++;
  }

  \%hist;
}

sub frequency_split {
  my %hist;
  my $pos = 0;
  for my $char (split //, $dna) {
    $hist{$pos ++}{$char} ++;
  }

  \%hist;
}

sub frequency_regmatch {
  my %hist;

  while ($dna =~ /(.)/g) {
    $hist{pos($dna)}{$1} ++;
  }

  \%hist;
}


cmpthese(-5, # Run each for at least 5 seconds
  { 
    substr => \&frequency_substr,
    split => \&frequency_split,
    regex => \&frequency_regmatch
  }
);

和一个样本结果:
         Rate  regex  split substr
regex  6254/s     --   -26%   -32%
split  8421/s    35%     --    -9%
substr 9240/s    48%    10%     --

结果 substr 出奇的快。 :)

关于perl - 在 Perl 中访问字符串中的单个字符时,是 substr 还是拆分为数组更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3983272/

相关文章:

c - 最好使用scanf或fgets?

java - 性能:单个还是多个 jar ?

perl - Perl 的 future ? (Perl 6,就业能力)

XML::Twig purge 在 perl 程序中不释放系统内存

string - 为什么将字符串称为 “strings”?

python - 如何将用户输入的字符串与列表中单词的字符(单个字母)进行比较?

.net - F#中的数组遍历

performance - hibernate - 卡在 HashMap.getEntry()

windows - 为什么重写二进制文件不起作用?

windows - 为什么我的 Perl 单行程序不能在 Windows 上运行?