Hi Monks,

I've always believed that joining a lot of strings together would be faster than concatenating them.

The idea is that concatenation creates a new copy of the string for each concatenation whereas join could, well join them, and only make one copy.

I created two test programs and was surprised by the result. Can anyone shed some light on this.

The only real difference between the programs is that one collects the chars in an array and then joins, the other concatenates them onto a string.


t_concat:
#!/usr/bin/perl #t_concat my $file = $ARGV[0]; local ($/) = undef; open FH, $file or die; my $data = <FH>; close FH; my $len = length($data); my $result; my $c; for($i = 0; $i < $len; $i++){ $c = substr $data, $i, 1; #concatenate onto result. $result .= $c; } print $result;

t_join:
#!/usr/bin/perl #t_join $file = $ARGV[0]; local ($/) = undef; open FH, $file or die; my $data = <FH>; close FH; my $len = length($data); my @result; $#result = $len; my $c; for($i = 0; $i < $len; $i++){ $c = substr $data, $i, 1; #put the string in an array for later join. $result[$i] = $c; } print join('', @result);

These results where consistent over 30 runs. Any wisdom?
t_join test.data > /dev/null 0.21s user 0.02s system 99% cpu 0.240 total
t_concat test.data > /dev/null 0.11s user 0.00s system 98% cpu 0.112 total


In reply to Concatenate or Join? by perldaemon

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.