Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: Concatenate or Join?

by dave_the_m (Prior)
on Nov 12, 2012 at 22:52 UTC ( #1003517=note: print w/replies, xml ) Need Help??

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)


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.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1003517]
and the monastery is silent...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (7)
As of 2018-03-17 16:58 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (225 votes). Check out past polls.