Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: Concatenate or Join?

by dave_the_m (Parson)
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)

Dave.


Comment on Re: Concatenate or Join?
Download Code
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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1003517]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (7)
As of 2014-08-23 16:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (174 votes), past polls