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.
#!/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;
#!/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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |