Here are a few alternatives assuming you cannot pre-split for your purpose.

My favorite hack is chop if I need speed and order does matter. It's about 4x faster than split and substantially faster than substr even if you have to reverse and copy for your needs. Better if you can avoid doing both, which you frequently can.

#! perl -sw use 5.010; use strict; use Benchmark qw[ cmpthese ]; our $LEN ||= 100; our $string = 'A' x $LEN; our @chars = split//, $string; cmpthese -3, { substr => q[ our $string; for ( 0 .. length $string ) { my $c = substr $string, $_, 1; } ], pre_split => q[ our @chars; for my $c ( @chars ) { ; } ], split => q[ our $string; my @chars = split //, $string; for my $c ( @chars ) { } ], unpack => q[ our $string; for ( unpack 'C*', $string ) { my $c = chr; } ], chop => q[ our $string; my $copy = $string; while( my $c = chop $copy ) { ; } ], rev_chop => q[ our $string; my $copy = reverse $string; while( my $c = chop $copy ) { ; } ], }; __END__ C:\test>byChar.pl Rate split unpack substr rev_chop chop p +re_split split 11018/s -- -74% -74% -81% -82% + -94% unpack 42513/s 286% -- -0% -26% -30% + -75% substr 42526/s 286% 0% -- -26% -30% + -75% rev_chop 57794/s 425% 36% 36% -- -5% + -66% chop 61056/s 454% 44% 44% 6% -- + -64% pre_split 171734/s 1459% 304% 304% 197% 181% + --

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
RIP PCW

In reply to Re: How to access each char in a string most quickly? by BrowserUk
in thread How to access each char in a string most quickly? by llancet

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.