in reply to Re: coding style suggestion
in thread coding style suggestion: (...)[1] vs. [...]->[1]
For ultimate speed, use the magic split regex ' '. Say what?
my $number = ( split ' ', $string, 3 )[1];
Saves another 1% to 10% or so and it's even easier to type, though a little harder to remember:)
From perlfunc:split
As a special case, specifying a PATTERN of space (' ') will split on white space just as split with no arguments does. Thus, split(' ') can be used to emulate awk's default behavior, whereas split(/ /) will give you as many null initial fields as there are leading spaces. A split on /\s+/ is like a split(' ') except that any leading whitespace produces a null first field. A split with no arguments really does a split(' ', $_) internally.
The very fact that there is a special case made for the splitting of whitespace delimited fields suggests that someone felt that this was worthwhile optimising. Who knows, maybe that someone was even LW himself.
#! perl -slw use strict; use Benchmark qw[ cmpthese ]; our $string = "zero one two three"; our $string = "zero one two three"; cmpthese( -5, { 'list\s+' => q[ my $num = ( split /\s+/, $string ) [1] ], 'anon\s+' => q[ my $num = [ split /\s+/, $string ]->[1] ], 'list\s+3' => q[ my $num = ( split /\s+/, $string, 3 ) [1] ], 'anon\s+3' => q[ my $num = [ split /\s+/, $string, 3 ]->[1] ], "list' '" => q[ my $num = ( split ' ', $string, ) [1] ], "list' '3" => q[ my $num = ( split ' ', $string, 3 ) [1] ], }); __END__ P:\test>test Rate anon\s+ anon\s+3 list' ' list\s+ list\s+3 list' '3 anon\s+ 13679/s -- -13% -47% -48% -56% -57% anon\s+3 15789/s 15% -- -39% -40% -50% -50% list' ' 25818/s 89% 64% -- -2% -18% -18% list\s+ 26330/s 92% 67% 2% -- -16% -16% list\s+3 31370/s 129% 99% 22% 19% -- -0% list' '3 31493/s 130% 99% 22% 20% 0% --
|
|---|