Skip to content

Instantly share code, notes, and snippets.

@sixfeetover
Created March 15, 2012 15:55
Show Gist options
  • Save sixfeetover/2044927 to your computer and use it in GitHub Desktop.
Save sixfeetover/2044927 to your computer and use it in GitHub Desktop.
Comparing [].join to string interpolation, different ruby versions
require 'benchmark'
n = 1_000_000
def key_arr(prefix, id, *suffixes)
[prefix, id, suffixes].flatten.compact.join ":"
end
def key_str1(prefix, id, *suffixes)
"#{prefix}:#{id}:#{suffixes.flatten.compact.join(':')}"
end
def key_str2(prefix, id, *suffixes)
s = suffixes.flatten.compact.join(':')
"#{prefix}:#{id}:#{s}"
end
def key_str3(prefix, id, *suffixes)
s = suffixes.join(':')
"#{prefix}:#{id}:#{s}"
end
pre = 'scenario'
id = 100
suff = ['class', 11231]
Benchmark.bm do |b|
b.report("array") do
n.times { key_arr(pre, id, suff) }
end
b.report("str1") do
n.times { key_str1(pre, id, suff) }
end
b.report("str2") do
n.times { key_str2(pre, id, suff) }
end
b.report("str3") do
n.times { key_str3(pre, id, suff) }
end
end
# 1.9.2-p0
user system total real
array 3.540000 0.010000 3.550000 ( 3.535814)
str1 3.380000 0.000000 3.380000 ( 3.384282)
str2 3.410000 0.000000 3.410000 ( 3.408285)
str3 2.620000 0.000000 2.620000 ( 2.620290)
# 1.9.2-p290
user system total real
array 3.310000 0.000000 3.310000 ( 3.307196)
str1 3.090000 0.000000 3.090000 ( 3.096069)
str2 3.120000 0.010000 3.130000 ( 3.119694)
str3 2.400000 0.000000 2.400000 ( 2.399246)
# 1.9.3-p125 vanilla
user system total real
array 3.410000 0.000000 3.410000 ( 3.413593)
str1 3.210000 0.000000 3.210000 ( 3.213534)
str2 3.180000 0.000000 3.180000 ( 3.187071)
str3 2.370000 0.000000 2.370000 ( 2.365893)
# 1.9.3-p125 falcon patch (https://gist.github.com/1688857)
user system total real
array 3.350000 0.000000 3.350000 ( 3.357074)
str1 3.020000 0.000000 3.020000 ( 3.016996)
str2 3.090000 0.000000 3.090000 ( 3.097042)
str3 2.320000 0.000000 2.320000 ( 2.315476)
# Rubinius head (March 2012)
user system total real
array 11.266902 0.020766 11.287668 ( 10.898232)
str1 8.546355 0.004628 8.550983 ( 8.443997)
str2 8.049362 0.001775 8.051137 ( 8.014934)
str3 5.590899 0.002207 5.593106 ( 5.569655)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment