[code-review] Benchmarking concatenation vs. interpolation

Adam Turoff <[email protected]> Thu, 4 Dec 2003 17:17:54 -0500
Newsgroups gmane.comp.lang.perl.code-review-ladder
Message-ID <[email protected]>
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?

Thanks,

Z.