Checking the performance of two ways to append string in Perl

  • A+
Category:Languages

I can use the two following ways in Perl:

my $str = "hello"; my $o1 = $str." world"; my $o2 = "$str world"; 

They do the same thing, although I was wondering if they are the same when speaking about performance. How can I check it? is there a special online tool?

 


Benchmark is the way to do this.

The two methods you're describing are called concatenation and interpolation, so we'll use those names as labels in the test.

#!/usr/bin/perl  use strict; use warnings;  use Benchmark;  my $str = 'hello';  # Run this two subroutines for at least 3 CPU seconds. # That "negative seconds" parameter is possibly the worst # interface in all of Perl! timethese(-3, {   concat => sub { $str . ' world' },   interp => sub { "$str world" }, }); 

And the results...

$ perl benchmark Benchmark: running concat, interp for at least 3 CPU seconds...     concat:  4 wallclock secs ( 3.16 usr +  0.00 sys =  3.16 CPU) @ 32680513.61/s (n=103270423)     interp:  3 wallclock secs ( 3.22 usr +  0.00 sys =  3.22 CPU) @ 29918605.90/s (n=96337911) 

Concatenation is slightly faster. But note that we needed to run around a hundred million tests in order to find this tiny difference. So I don't think you really need to worry here.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: