Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: foreach (each character in string..)?

by Abigail-II (Bishop)
on Jan 21, 2004 at 14:31 UTC ( #322893=note: print w/replies, xml ) Need Help??


in reply to Re: foreach (each character in string..)?
in thread foreach (each character in string..)?

I think the best way is
What's your definition of "best way"? split // seems to be the most common idiom. And the "ugly" way, use of substr seems to be the fastest according to the following benchmark:
#!/usr/bin/perl use strict; use warnings; use Benchmark qw /timethese cmpthese/; our $char; for my $size (4, 16, 64, 256, 1024) { print "Iterating over a string of length $size.\n"; our $str = "-" x $size; cmpthese -5 => { split => 'for my $c (split // => $str) {$char = $c}', for => 'for my $c ($str =~ /(.)/g) {$char = $c}', while => 'while ($str =~ /(.)/g) {$char = $1}', substr => 'for my $i (0 .. (length ($str) - 1)) {$char = substr $str +, $i, 1}', } } __END__ Iterating over a string of length 4. Rate split for while substr split 157193/s -- -9% -20% -44% for 173109/s 10% -- -12% -38% while 197371/s 26% 14% -- -30% substr 280339/s 78% 62% 42% -- Iterating over a string of length 16. Rate split for while substr split 47828/s -- -3% -12% -55% for 49213/s 3% -- -10% -54% while 54413/s 14% 11% -- -49% substr 107090/s 124% 118% 97% -- Iterating over a string of length 64. Rate split for while substr split 12882/s -- -5% -7% -56% for 13574/s 5% -- -2% -54% while 13798/s 7% 2% -- -53% substr 29595/s 130% 118% 114% -- Iterating over a string of length 256. Rate split for while substr split 3244/s -- -5% -7% -59% for 3420/s 5% -- -2% -57% while 3483/s 7% 2% -- -56% substr 7951/s 145% 132% 128% -- Iterating over a string of length 1024. Rate split for while substr split 818/s -- -4% -7% -59% for 850/s 4% -- -3% -58% while 875/s 7% 3% -- -57% substr 2013/s 146% 137% 130% --
I must say, the performance of substr surprises me, and I find the difference between substr and other methods suspect, but I can't find any flaw in the benchmark.

Abigail

Replies are listed 'Best First'.
Re^2: foreach (each character in string..)?
by atoomic (Initiate) on Dec 01, 2018 at 00:33 UTC

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://322893]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2019-11-18 20:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Strict and warnings: which comes first?



    Results (92 votes). Check out past polls.

    Notices?