So our favourite construct doesn't do what we think it will....print "Hey" if $responce eq "hi"; # is optimised/parsed to: (($responce eq "hi") and print("Hey"));
I couldn't get a definate answer out of Benchmark, but generally the fastest method is:
if ($responce eq "hi") { print "Hey" }
But the others aren't far behind
You would expect the second one of those to be faster if anything since that is what the first one is changed to, but maybe my tests were screwy.print "Hey" if $responce eq "hi"; (($responce eq "hi") and print("Hey");
Tests run on linux 5.005_03
Update: Okay I had another look at my Deparse results in relation to Adam's reply below. I generally use perl -MO=Deparse,-p -e ... since it adds extra bracketing and things so I can tell exactly how things are working in terms of precedence and stuff. It seems that using -p rearranges the foo if blah; to blah and foo but without -p, Deparse leaves it alone. So my question is, which result is more correct, does perl do the full transformation like Deparse,-p or does it just do the equivilent to plain Deparse before the next stage of complimation?
Here's where my benchmarks came from:
Like I said it wasn't totally constant, so what did I do wrong in creating those benchmarks?my @foo = map {int rand 3} 1..1000; timethese(-15, { one => 'for (@foo) { print "$_\n" if $_; }', two => 'for (@foo) { if ($_) {print "$_\n";} }', three => 'for (@foo) { ($_ and print("\n")); }', } ); __END__ Result: one: 15 wallclock secs (14.99 usr + 0.01 sys = 15.00 CPU) @ 9421.60 +/s (n=141324) two: 16 wallclock secs (15.01 usr + -0.01 sys = 15.00 CPU) @ 9217.53 +/s (n=138263) three: 14 wallclock secs (15.43 usr + 0.01 sys = 15.44 CPU) @ 8842.75 +/s (n=136532) another run one: 6 wallclock secs ( 7.00 usr + 0.01 sys = 7.01 CPU) @ 9369.33 +/s (n=65679) three: 7 wallclock secs ( 7.57 usr + 0.00 sys = 7.57 CPU) @ 9237.78 +/s (n=69930) two: 7 wallclock secs ( 7.44 usr + 0.00 sys = 7.44 CPU) @ 8758.33 +/s (n=65162) and another two: 9 wallclock secs ( 7.00 usr + 0.00 sys = 7.00 CPU) @ 9757.14 +/s (n=68300) one: 6 wallclock secs ( 7.00 usr + 0.01 sys = 7.01 CPU) @ 9133.24 +/s (n=64024) three: 5 wallclock secs ( 7.06 usr + 0.00 sys = 7.06 CPU) @ 8828.47 +/s (n=62329)
In reply to Re: Loops and speed
by repson
in thread Loops and speed
by damian1301
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |