Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
The following code I wrote as a simple test to compare the difference between the 2 "for loop" methods of syntax.
Here are the results returned when run:#!/usr/bin/perl -w use Benchmark; use strict; my $results = timethese( 30, { a => sub{my $total = 0; $total += $_ for(1..1e6);}, b => sub{my $total = 0; for(1..1e6){$total += $_;}}, } );
Does anyone have any idea why the method is subroutine two() is slower in execution than the method in subroutine one()?Benchmark: timing 30 iterations of a, b... a: 8 wallclock secs ( 8.30 usr + 0.00 sys = 8.30 CPU) @ 3 +.62/s (n=30) b: 9 wallclock secs ( 9.03 usr + 0.02 sys = 9.05 CPU) @ 3 +.32/s (n=30)
The recorded difference might not seem like much but the larger the array context is the larger the delta between the two becomes. Try changing the "1e6" to "1e7" and you can see what I am talking about.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Benchmarking for loops?
by chromatic (Archbishop) on Jul 13, 2004 at 00:00 UTC | |
by Fletch (Bishop) on Jul 13, 2004 at 00:10 UTC | |
by ysth (Canon) on Jul 13, 2004 at 00:33 UTC | |
by chromatic (Archbishop) on Jul 13, 2004 at 05:48 UTC | |
by ysth (Canon) on Jul 13, 2004 at 06:18 UTC | |
by stvn (Monsignor) on Jul 13, 2004 at 03:02 UTC | |
by ysth (Canon) on Jul 13, 2004 at 06:28 UTC | |
|
Re: Benchmarking for loops?
by keszler (Priest) on Jul 13, 2004 at 00:27 UTC | |
by graff (Chancellor) on Jul 13, 2004 at 01:37 UTC | |
by keszler (Priest) on Jul 13, 2004 at 02:40 UTC | |
|
Re: Benchmarking for loops?
by ysth (Canon) on Jul 13, 2004 at 00:02 UTC |