in reply to Very basic question on performance
Your examples do not produce the same results. The first one multiplies $x_sq * $y_sq, while the second example adds the equivalent terms. In my benchmark I changed the second code snippet to multiply instead.
The Benchmark module is sort of the standard module used in testing and comparing code snippets. The following script is an example of how to use it to check what your intuition is telling you:
use Inline C => 'DATA'; use Benchmark 'cmpthese'; sub vdiag { my( $x, $y ) = @_; my $x_sq = $x * $x; my $y_sq = $y * $y; my $prod = $x_sq * $y_sq; my $res = sqrt($prod); return $res; } sub ediag { return sqrt( $_[0] * $_[0] * $_[1] * $_[1] ); } cmpthese( -5, { cdiag => 'cdiag(7,9)', vdiag => 'vdiag(7,9)', ediag => 'ediag(7,9)', } ); __DATA__ __C__ #include <math.h> double cdiag ( double x, double y ) { double x_sq = x * x; double y_sq = y * y; double prod = x_sq * y_sq; return sqrt(prod); }
That produces the following comparison table:
$ ./mytest.pl Rate vdiag ediag cdiag vdiag 1589859/s -- -49% -82% ediag 3127854/s 97% -- -64% cdiag 8603134/s 441% 175% --
So your intuition was correct, that declaring a bunch of variables takes a little longer. But you do have to put it in perspective; 1589859 iterations per second is already very fast. And if you are really concerned with performance in a tight loop or something, eliminating the clarity that comes from using named variables is, in this case, not the most effective solution. The C solution is still readable, and achieves 8603134 iterations per second. Write your Perl how you would like to read it back in six months. And when performance is a real bottleneck, take your biggest swing at the problem first.
Dave
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Very basic question on performance
by AnomalousMonk (Archbishop) on Mar 14, 2014 at 13:58 UTC | |
by davido (Cardinal) on Mar 14, 2014 at 17:05 UTC | |
by AnomalousMonk (Archbishop) on Mar 15, 2014 at 11:59 UTC | |
|
Re^2: Very basic question on performance
by Laurent_R (Canon) on Mar 14, 2014 at 09:37 UTC | |
by davido (Cardinal) on Mar 14, 2014 at 15:19 UTC | |
by morrin (Acolyte) on Mar 14, 2014 at 15:28 UTC | |
by Laurent_R (Canon) on Mar 14, 2014 at 18:42 UTC | |
by davido (Cardinal) on Mar 14, 2014 at 18:57 UTC | |
by Laurent_R (Canon) on Mar 14, 2014 at 20:01 UTC | |
|
Re^2: Very basic question on performance
by Old_Gray_Bear (Bishop) on Mar 15, 2014 at 23:30 UTC |