Re: [code-review] Benchmarking concatenation vs. interpolation

Abigail <[email protected]> Thu, 4 Dec 2003 23:43:17 +0100
Newsgroups gmane.comp.lang.perl.code-review-ladder
Message-ID <[email protected]>
On Thu, Dec 04, 2003 at 05:17:54PM -0500, Adam Turoff wrote:
> Hi,
> 
> I'm doing a bit of refactoring, and I wanted to compare the hopelessly 
> unreadable technique of successive concatenation against a single
> interpolation.  I have this benchmark program, and I'd like a sanity check:
> 
> 	#!/usr/bin/perl -w
> 
> 	use strict;
> 	use Benchmark qw(:all);
> 
> 	our $border = 0;
> 	our $cellspacing = 0;
> 	our $cellpadding = 0;
> 
> 	cmpthese (-5, {
> 	    interp => sub {
> 		my $table = qq(
> 			<table border="$border" cellspacing="$cellspacing" 
> 			       cellpadding="$cellpadding">
> 			</table>
> 		);
> 	    },
> 	    concat => sub {
> 		my $table = '<table border="' . $border . '"';
> 		$table .= ' cellspacing="' . $cellspacing . '"';
> 		$table .= ' cellpadding="' . $cellpadding . '">' . "\n";
> 		$table .= '</table>' . "\n";
> 	    },
> 	});
> 
> And here are the results on my iBook:
> 
> 		   Rate concat interp
> 	concat 184391/s     --   -39%
> 	interp 300413/s    63%     --
> 
> 
> Now, I'd expect a single interpolation to be faster than multiple
> concatenation operations.  But should concatenation be *THAT* much
> faster in this comparison?  
> 
> Is this a valid benchmark?


Not by a long shot. First of all, the final strings will differ, the 
string assigned in the 'interp' case has far more spaces that the 
'concat' case. But what's worse, the 'concat' case has 4 assignments,
while the 'interp' case has only one.

I restructured your program into:

        #!/usr/bin/perl

        use strict;
        use warnings;
        no warnings qw /syntax/;


        use Benchmark qw(:all);

        our $border = 0;
        our $cellspacing = 0;
        our $cellpadding = 0;

        our ($table1, $table2);

        cmpthese (-5, {
            interp => sub {
                $table1 =
        qq (<table border="$border" cellspacing="$cellspacing" cellpadding="$cellpadding"> </table>);
            },    
            concat => sub {
                $table2  = '<table border="' . $border . '" cellspacing="' .
                             $cellspacing . '" cellpadding="' . $cellpadding .
                             '"> </table>';
            },
        });   

        die "Unequal" unless $table1 eq $table2;

        __END__


which leads to:

                   Rate interp concat
        interp 445985/s     --    -2%
        concat 454956/s     2%     --


which is far less of a difference.



Abigail