Skip to content

Instantly share code, notes, and snippets.

@porras
Created July 28, 2015 19:02
Show Gist options
  • Save porras/ea350ac64b3e03241726 to your computer and use it in GitHub Desktop.
Save porras/ea350ac64b3e03241726 to your computer and use it in GitHub Desktop.
require "./src/benchmark"
def repetition1(ary, times)
ary = typeof(ary).new(ary.length * times)
times.times do
ary += ary
end
ary
end
def repetition2(ary, times)
ary = typeof(ary).new(ary.length * times)
times.times do
ary.concat(ary)
end
ary
end
def repetition3(ary, times)
typeof(ary).build(ary.length * times) do |buffer|
times.times do
buffer.copy_from(buffer, ary.length)
buffer += ary.length
end
ary.length * times
end
end
def repetition4(ary, times)
total_length = ary.length * times
typeof(ary).build(total_length) do |buffer|
buffer.copy_from(ary.buffer, ary.length)
n = ary.length
while n <= total_length / 2
(buffer + n).copy_from(buffer, n)
n *= 2
end
(buffer + n).copy_from(buffer, total_length - n)
total_length
end
end
[10, 100, 1000, 10000, 10000].each do |n|
puts "# #{n} times an array of #{n} items"
ary = (1..n).to_a
Benchmark.ips do |x|
x.report("with +=") { repetition1(ary, n) }
x.report("with concat") { repetition2(ary, n) }
x.report("with build") { repetition3(ary, n) }
x.report("with incremental build") { repetition4(ary, n) }
end
puts
end
# 10 times an array of 10 items
with += 497041.18 (± 19510.25) 2.54× slower
with concat 1219959.79 (± 21276.69) 1.03× slower
with build 1157644.76 (± 47725.08) 1.09× slower
with incremental build 1262033.53 (± 27700.35) fastest
# 100 times an array of 100 items
with += 27718.62 (± 805.97) fastest
with concat 21107.59 (± 468.77) 1.31× slower
with build 20454.81 (± 421.33) 1.36× slower
with incremental build 20937.18 (± 483.42) 1.32× slower
# 1000 times an array of 1000 items
with += 1354.50 (± 39.02) fastest
with concat 1153.33 (± 62.11) 1.17× slower
with build 715.43 (± 37.43) 1.89× slower
with incremental build 650.58 (± 35.14) 2.08× slower
# 10000 times an array of 10000 items
with += 16.49 (± 2.57) fastest
with concat 15.71 (± 4.57) 1.05× slower
with build 8.13 (± 1.70) 2.03× slower
with incremental build 6.58 (± 1.36) 2.50× slower
# 10000 times an array of 10000 items
with += 17.20 (± 1.87) fastest
with concat 15.94 (± 4.34) 1.08× slower
with build 8.16 (± 1.80) 2.11× slower
with incremental build 6.70 (± 1.22) 2.57× slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment