Posted by: songbard | August 23, 2008

Perl : A foreach loop normally saves time!

Script:

#!/usr/bin/perl

# use Benchmark module
use Benchmark qw (:all);

# time 3 different versions of the same code
cmpthese (1000, {
‘foreach’ => ‘foreach $x (1…5000)
{
sin($x/($x+2));
}’,
‘while’ => ‘$x=1;
while ($x <= 5000)
{
sin ($x/($x+2));
$x++;
}’,
‘for’ => ‘for ($x=1; $x<=5000; $x++)
{
sin ($x/($x+2));
}’,
});
…………………………..
…………………………..

Result:

Rate for while foreach
for 400/s — -2% -17%
while 407/s 2% — -16%
foreach 483/s 21% 19% —

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: