http://qs321.pair.com?node_id=362535


in reply to Style or Clarity?

If you're concerned that the clearer version should be slower, you should benchmark it:
#!/usr/bin/perl -w use strict; use Benchmark; sub clarity { my $tmp = shift; my $ret = 0; if($tmp eq 'F'){ ; # do nothing, spot held for clarity }elsif($tmp =~ /[MICL]/){ $ret = 1; }else{ $ret = 2; } return $ret; } sub speed { my $tmp = shift; my $ret = 0; if($tmp =~ /[MICL]/){ $ret = 1; }else{ $ret = 2; } return $ret; } timethese(100_000, { clarity => sub { clarity('F'); clarity('M'); clarity('J'); }, speed => sub { speed('F'); speed('M'); speed('J'); }, } );
Benchmark: timing 100000 iterations of clarity, speed... clarity: 2 wallclock secs ( 1.74 usr + 0.00 sys = 1.74 CPU) @ 57 +471.26/s (n=100000) speed: 2 wallclock secs ( 1.78 usr + 0.00 sys = 1.78 CPU) @ 56 +179.78/s (n=100000)

So it appears that, at least in this test, the clearer version is a little faster. Your tests can simulate your environment better, but it looks like both chunks of code are really close to the same speed, and you should code however you find most clear and enjoyable. :)

Update: Abigail-II's right, this benchmark is a little off, and in fact a first attempt to correct it makes speed slightly faster, though it's still within a few percent. Still, you can easily see how to modify this to benchmark your actual functions and see if there is enough of a speed difference to sacrifice clarity.