http://qs321.pair.com?node_id=209382


in reply to Re: array pre-allocation trick
in thread array pre-allocation trick

Your benchmark is utterly flawed. You aren't measuring what you think you are measuring. The following benchmark suggest that preallocating is actually a tad bit slower, and that using slices loses. Assigning is a little faster than pushing.
#!/usr/bin/perl use strict; use warnings; use Benchmark qw /cmpthese timethese/; our $size = 100_000; cmpthese timethese (-10 => { push => 'my @arr; push @arr => $_ for 0 .. $::size - 1', assign => 'my @arr; $arr [$_] = $_ for 0 .. $::size - 1', assignpre => 'my @arr; $#arr = $::size - 1; $arr [$_] = $_ for 0 .. $::size - 1', slice => 'my @arr; @arr [0 .. $::size - 1] = (0 .. $::size - +1)', slicepre => 'my @arr; $#arr = $::size - 1; @arr [0 .. $::size - 1] = (0 .. $::size - +1)', } => 'none'); __END__ Rate slicepre slice push assignpre assign slicepre 3.82/s -- -1% -37% -40% -41% slice 3.87/s 1% -- -36% -39% -40% push 6.08/s 59% 57% -- -4% -5% assignpre 6.36/s 66% 64% 5% -- -1% assign 6.44/s 68% 66% 6% 1% --

Abigail