Hi all,
In a recent node there was some discussion about the different ways to get the count of the number of elements in an array. In that thread I expressed my personal preference for scalar(@array) over $#array + 1 or $size = @array. I didn't have any performance timings, so I figured I should see if there really is a difference. This is my timing code:
use strict; use Benchmark; my @array = (1..10000000); timethese(100000000, { 'scalar' => \&size_scalar, 'index' => \&size_index, 'context' => \&size_context } ); sub size_context { my $val1 = @array; } sub size_index { my $val2 = $#array + 1; } sub size_scalar { my $val3 = scalar(@array); }
context: 30.52 usr + 0.00 sys = 30.52 CPU @ 3277076.85/s<br> index: 42.11 usr + 0.00 sys = 42.11 CPU @ 2374732.84/s<br> scalar: 53.44 usr + 0.00 sys = 53.44 CPU @ 1871327.52/s
So, two questions here. First, is my test doing a reasonable job of timing? I don't do benchmarks like this often, so I'm worried I've hashed it up. Second, is there any obvious reason why the difference? Is scalar(@array) is slower because it requires a function call?
-TatsIn reply to Timing of Array-Size Determination Methods by Itatsumaki
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |