http://www.perlmonks.org?node_id=1003517


in reply to Concatenate or Join?

You are not comparing concat against join. You are comparing concat against creating and repeatedly extending an array and joining.

With a level playing field, join is quicker:

use Benchmark; my @a = ('x') x 1_000_000; timethese(100, { 'concat' => sub { my $s; $s .= $_ for @a }, 'join' => sub { my $s = join '', @a }, },); __END__ concat: 11 wallclock secs (10.86 usr + 0.01 sys = 10.87 CPU) @ 9 +.20/s (n=100) join: 4 wallclock secs ( 4.01 usr + 0.00 sys = 4.01 CPU) @ 24 +.94/s (n=100)

Dave.

Replies are listed 'Best First'.
Re^2: Concatenate or Join?
by perldaemon (Novice) on Nov 13, 2012 at 00:43 UTC

    Thanks Dave for the input. I was comparing a situation where I can either fill an array as I parse through data and then later join, or just concatenate as I go.

    I agree that if the array is already created then it is certainly faster to join. But if you have to build the array just so you can join the elements later, it looks like concatenation is faster. Or am I missing something?

      In that case, doing the concat (and thus skipping creating the array) could be faster, but would probably depend on such factors as the pattern of string lengths, and whether you could presize the string.

      Dave.