Consider the informal benchmark
use Benchmark qw|:all|; my @a = (1..1_000_000); my $b; my $c = 'x' x 1_000_000; my $d; cmpthese( 5, { ary => sub { for my $i (0..1_000_000-501) { $b = $a[$i] - $a[$i+500]; } }, substr => sub { for my $i (0..1_000_000-501) { $d = substr($c,$i,1) . substr($c,$i+500,1); } }, unpack => sub { my @b = unpack 'c*', $c }, split => sub { my @b = split //, $c } } );
On my arthritic PIII machine, I get
Benchmark: timing 5 iterations of ary, split, substr, unpack... ary: 8 wallclock secs ( 8.62 usr + 0.00 sys = 8.62 CPU) @ 0 +.58/s (n=5) split: 26 wallclock secs (24.93 usr + 0.33 sys = 25.26 CPU) @ 0 +.20/s (n=5) substr: 11 wallclock secs (11.64 usr + 0.00 sys = 11.64 CPU) @ 0 +.43/s (n=5) unpack: 7 wallclock secs ( 6.14 usr + 0.03 sys = 6.17 CPU) @ 0 +.81/s (n=5) s/iter split substr ary unpack split 5.05 -- -54% -66% -76% substr 2.33 117% -- -26% -47% ary 1.72 193% 35% -- -28% unpack 1.23 309% 89% 40% --
This says that, for the ops between elements $i and $i+500 I picked, an array rep is faster than a string rep, but the overhead of breaking a string into an array will negate that advantage. The best you could do on my machine with these algorithms and ops it is to move along the string at about 500_000 chars/sec.

Another solution that has not been mentioned yet is using a regexp. From perlretut:

while ($dna =~ /(?=A.{500}T)./g) { print "Got an AT match at position ", pos $dna, "\n"; }
Update Fixed regexp.

-Mark


In reply to Re: character-by-character in a huge file by kvale
in thread character-by-character in a huge file by mushnik

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.