Skip to content

Instantly share code, notes, and snippets.

@chrismytton
Created August 25, 2010 19:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrismytton/550144 to your computer and use it in GitHub Desktop.
Save chrismytton/550144 to your computer and use it in GitHub Desktop.
[/Users/chris/Code/Ruby/gist-550144 (master)] ruby-1.9.2-p0
$ time php php_string.php > /dev/null
real 0m0.237s
user 0m0.218s
sys 0m0.017s
[/Users/chris/Code/Ruby/gist-550144 (master)] ruby-1.9.2-p0
$ time php php_array.php > /dev/null
real 0m0.249s
user 0m0.221s
sys 0m0.023s
<?php
$names = array('Fred', 'Bob', 'Harry', 'Jim', 'Tony', 'Alf', 'Richard', 'John', 'David', 'Ralf', 'Peter');
$bigArray = array();
for ($i = 1; $i <= 50000; $i++) {
$bigArray[] = $names[rand(0, count($names) - 1)];
}
echo implode("\n", $bigArray);
<?php
$names = array('Fred', 'Bob', 'Harry', 'Jim', 'Tony', 'Alf', 'Richard', 'John', 'David', 'Ralf', 'Peter');
$bigString = "";
for ($i = 1; $i <= 50000; $i++) {
$bigString .= $names[rand(0, count($names) - 1)] . "\n";
}
echo $bigString;
[/Users/chris/Code/Ruby/string_vs_array] ruby-1.9.2-p0
$ time ruby string.rb > /dev/null
real 0m5.545s
user 0m2.553s
sys 0m2.921s
[/Users/chris/Code/Ruby/string_vs_array] ruby-1.9.2-p0
$ time ruby array.rb > /dev/null
real 0m0.047s
user 0m0.035s
sys 0m0.009s
names = %w{Fred Bob Harry Jim Tony Alf Richard John David Ralf Peter}
big_array = []
1.upto(50000) do
big_array << names[rand(names.size)]
end
puts big_array.join("\n")
names = %w{Fred Bob Harry Jim Tony Alf Richard John David Ralf Peter}
big_string = ""
1.upto(50000) do
big_string += "#{names[rand(names.size)]}\n"
end
puts big_string
@tholder
Copy link

tholder commented Aug 25, 2010

This issue isn't unique to ruby, lots of languages seem to behave the same and my crude understanding is that it's something to do with memory allocation and the heap. We used to have the same problem with classic asp and VB and a quick search suggests it's an issue in Python as well http://www.skymind.com/~ocrow/python_string/

PHP doesn't suffer from this http://stackoverflow.com/questions/124067/php-string-concatenation-performance

@chrismytton
Copy link
Author

PHP is certainly faster overall in my very synthetic benchmark. Weirdly it seems (ever so slightly) slower using an array, and neither string nor array in PHP can match the raw speed of the Ruby array...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment