Recently I was looking for the fastest way to clear an array I was using as a buffer. It had a specific length, it needed to have 'undef' for 'empty' values, and it may or may not have current values, plus it is going to be immediately refilled with 'real' values.
This isn't really something that's often needed: Anything is fast. But I was trying to squeeze every last bit of performance out of this code, so it mattered a bit.
Anyway, asking on the chatterbox got me several answers: Everyone seems to have an opinion, no one seems to know.
So I benchmarked. Here are the results for your trivia pleasure:
#!/usr/bin/perl use strict; use warnings; use Benchmark qw(cmpthese); my @working; $#working = 100; cmpthese( -10, { assign => '@working = (); $working[$_] = $_ foreach ( 0.. +.100 );', assign_undef => 'undef @working; $working[$_] = $_ foreach ( 0. +..100 );', assign_length => '@working = ()[0...100]; $working[$_] = $_ fore +ach ( 0...100 );', using_x => '@working = (undef) x 101; $working[$_] = $_ fo +reach ( 0...100 );', x_with_value => '@working = 1 x 101; $working[$_] = $_ foreach +( 0...100 );', } );
(The last is just to see if pre-filling with something approaching valid values makes a difference.)
Results:
Rate using_x assign_undef x_with_value assign_length + assign using_x 21456/s -- -5% -7% -12% + -13% assign_undef 22605/s 5% -- -2% -8% + -8% x_with_value 23108/s 8% 2% -- -5% + -6% assign_length 24448/s 14% 8% 6% -- + -1% assign 24637/s 15% 9% 7% 1% + --
Rate using_x assign_undef assign_length x_with_value + assign using_x 35870/s -- -1% -1% -2% + -4% assign_undef 36133/s 1% -- -0% -1% + -4% assign_length 36298/s 1% 0% -- -1% + -3% x_with_value 36540/s 2% 1% 1% -- + -3% assign 37497/s 5% 4% 3% 3% + --
Note these results are about as stable as you would expect seeing those close numbers: That is, not very. 'Assign' and 'assign_undef' are generally the fastest, but expect pair switching between any pair on any run. (With occasional far-switching.)
I went with 'assign'.
Edit: Updated to fix some testing methodology problems noted by ikegami below. Thanks.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Emptying (and refilling) an array.
by Jenda (Abbot) on Jan 12, 2009 at 16:24 UTC | |
|
Re: Emptying (and refilling) an array.
by ikegami (Patriarch) on Jan 12, 2009 at 15:51 UTC | |
by DStaal (Chaplain) on Jan 12, 2009 at 16:22 UTC | |
by ikegami (Patriarch) on Jan 12, 2009 at 16:38 UTC | |
by JavaFan (Canon) on Jan 12, 2009 at 16:43 UTC | |
|
Re: Emptying (and refilling) an array.
by Zen (Deacon) on Jan 12, 2009 at 19:46 UTC | |
|
Re: Emptying (and refilling) an array.
by JavaFan (Canon) on Jan 12, 2009 at 15:28 UTC | |
by DStaal (Chaplain) on Jan 12, 2009 at 15:46 UTC | |
by JavaFan (Canon) on Jan 12, 2009 at 15:57 UTC | |
by massa (Hermit) on Jan 12, 2009 at 16:01 UTC |