General discussion

Locked

Use join to concatenate list elements

By Mark W. Kaelin Editor ·
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.

This conversation is currently closed to new comments.

2 total posts (Page 1 of 1)  
| Thread display: Collapse - | Expand +

All Comments

Collapse -

Join efficiency

by jaralston3 In reply to Use join to concatenate l ...

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

Collapse -

Join efficiency answer

by Mark W. Kaelin Editor In reply to Join efficiency

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:

<code>
($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";
</code>

Back to Web Development Forum
2 total posts (Page 1 of 1)  

Related Discussions

Related Forums