Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Concatenate or Join?

by johngg (Abbot)
on Nov 12, 2012 at 20:38 UTC ( #1003505=note: print w/replies, xml ) Need Help??


in reply to Concatenate or Join?

Reducing the join and concatenation to a simple example without any file i/o, I don't get the same result when Benchmarking.

use strict; use warnings; use Benchmark qw{ cmpthese }; my @arr = ( q{abc} ) x 10000; cmpthese( -5, { concat => sub { my $ret; $ret .= $_ for @arr; return $ret; }, join => sub { my $ret = join q{}, @arr; return $ret; }, } );
$ ./spw1003500 Rate concat join concat 994/s -- -70% join 3310/s 233% -- $

Perhaps something else is skewing your timing.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: Concatenate or Join?
by tobyink (Abbot) on Nov 12, 2012 at 20:54 UTC

    It depends what you're doing really. In your example, join beats concat, but that's because you are looping through an array. Here though, concatenation beats it (albeit only by about 10%):

    use strict; use warnings; use Benchmark qw{ cmpthese }; sub foo { 'abc' }; sub bar { 'def' }; cmpthese( -3, { concat => sub { my $ret = foo().bar(); return $ret; }, join => sub { my $ret = join q{}, foo(), bar(); return $ret; }, });

    And here (thanks to the Perl compiler being so good at constant folding) concatenation is more than twice as fast as join:

    use strict; use warnings; use Benchmark qw{ cmpthese }; sub foo () { 'abc' }; sub bar () { 'def' }; cmpthese( -3, { concat => sub { my $ret = foo . bar; return $ret; }, join => sub { my $ret = join q{}, foo, bar; return $ret; }, });
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1003505]
help
Chatterbox?
[choroba]: My recent record is 10km in 1 hour :)
[perldigious]: Nice erix... perldigious' legs are so sore from portaging his kayak from place to place last weekend he can barely hobble 12m. :-)
[erix]: you're faster than me then :)
[erix]: well, at the moment, that is :)
[erix]: I should lose some weight although I keep telling myself that I'm doing extra training by lugging it along
[erix]: I saw a common kingfisher and a couple of bullfinches
[erix]: bullfinch ( a male and a female )
erix learned the word 'portaging' not so long ago (from vikings lugging their ships from one river-system to another)

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (8)
As of 2017-05-24 12:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?