|The stupid question is the question not asked|
Re: Using foreach to process a hashby DigitalKitty (Parson)
|on Oct 22, 2006 at 06:03 UTC||Need Help??|
Benchmark: timing 1000000 iterations of foreach_loop, while_each_loop...
foreach_loop: 0 wallclock secs ( 1.16 usr + 0.00 sys = 1.16 CPU) @ 864304.24/s (n=1000000)
while_each_loop: 1 wallclock secs ( 0.51 usr + 0.00 sys = 0.51 CPU) @ 1941747.57/s (n=1000000)
In order to ascertain which function is more efficient, look at the output and you'll see: sys =n.nn CPU. The Benchmark module functions by executing your code as many times as the first parameter after the timethese() subroutine indicates then calculates an average based upon the amount of time it took. It then reports on the total amount of time taken. As one can see, the while_each loop executes faster and that would be a wise choice when iterating over an exceptionally large hash.
Update: In the event you see '(warning: too few iterations for a reliable count)' in the output, simply augment the number of code executions in the timethese() function.
2nd Update: Thanks jdporter and blazar. I rushed through this example and hadn't noticed the small bugs I had introduced by doing so.
Hope this helps,