Discussion Locked

Use join to concatenate list elements

0 helpful
2 replies
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.
The Dec. 10, Perl TechMail discusses the join function. Have you ever used Perl's join function to concatenate list elements? Tell us about your experience.

2 replies

by jaralston3

You say: "Using join with a null string is the most efficient way to concatenate
strings together."

Is join more efficient than the concantenation operator "."? If so, efficient in what way: CPU cycles, memory usage, programming time?

John

by Mark W. Kaelin

I asked the tip author to respond:

I whipped up some quickie test code to see which was more efficient. Here
are the results:

Join did 58814 in 1 second
Array join did 52054 in 1 second
Concatenate did 56446 in 1 second
For loop did 15068in 1 second

I concluded from this test that join did about 2000 more operations per
second than concatenate did. If you didn't know how much data you were
going to join (such as joining all the elements of an array) then join is
much faster (58K vs. 15K per second) than using a for loop.

Here is the test code that I devised:

($a, $b, $c, $d, $e, $f) = qw(oneoneone twotwotwo threethreethree fourfourfour fivefivefive sixsixsix); @a = ($a, $b, $c, $d, $e, $f);

$start = time;

1 while ($start == time);

$start = time; $count = 0;
while ($start == time)
{
$count++;
$r = join '', $a, $b, $c, $d, $e, $f;
}

print "Join did $count in 1 second\n";

$start = time;

1 while ($start == time);

$start = time; $count = 0;
while ($start == time)
{
$count++;
$r = join '', @a;
}

print "Array join did $count in 1 second\n";

$start = time;

1 while ($start == time);

$start = time; $count = 0;
while ($start == time)
{
$count++;
$r =$a . $b . $c . $d . $e . $f;
}

print "Concatenate did $count in 1 second\n";

$start = time;

1 while ($start == time);

$start = time; $count = 0;
while ($start == time)
{
$count++;
for ($r = '', $i = 0; $a[$i]; $i++) { $r .= $a[$i]; }
}

print "For loop did $count in 1 second\n";

This discussion is closed to new replies.