in reply to Re: foreach (each character in string..)?
in thread foreach (each character in string..)?
I think the best way isWhat'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:
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.#!/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% --
Abigail
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: foreach (each character in string..)?
by atoomic (Initiate) on Dec 01, 2018 at 00:33 UTC |
In Section
Seekers of Perl Wisdom