Skip to content

Instantly share code, notes, and snippets.

@michaelherold
Last active August 18, 2017 16:58
Show Gist options
  • Save michaelherold/f149080fb4ae90e7a5516ff98154f852 to your computer and use it in GitHub Desktop.
Save michaelherold/f149080fb4ae90e7a5516ff98154f852 to your computer and use it in GitHub Desktop.
Conditional string building in Ruby
#!/usr/bin/env ruby
# gem install benchmark-ips benchmark-memory
# ruby benchmark.rb
require "benchmark/ips"
require "benchmark/memory"
Benchmark.ips do |x|
x.report("join") do
blah = []
blah << "cancelled"
blah << "(reason)" if 1.odd?
blah.join(" ")
end
x.report("tap") do
"cancelled".tap do |s|
s << " (reason)" if 1.odd?
end
end
x.compare!
end
Benchmark.memory do |x|
x.report("join") do
blah = []
blah << "cancelled"
blah << "(reason)" if 1.odd?
blah.join(" ")
end
x.report("tap") do
"cancelled".tap do |s|
s << " (reason)" if 1.odd?
end
end
x.compare!
end
# ruby 2.2.3p173
# Warming up --------------------------------------
# join 69.404k i/100ms
# tap 118.522k i/100ms
# Calculating -------------------------------------
# join 957.332k (± 3.4%) i/s - 4.789M in 5.008177s
# tap 2.105M (± 3.5%) i/s - 10.548M in 5.016827s
#
# Comparison:
# tap: 2105236.9 i/s
# join: 957331.5 i/s - 2.20x slower
#
# Calculating -------------------------------------
# join 329.000 memsize ( 0.000 retained)
# 5.000 objects ( 0.000 retained)
# 4.000 strings ( 0.000 retained)
# tap 80.000 memsize ( 0.000 retained)
# 2.000 objects ( 0.000 retained)
# 2.000 strings ( 0.000 retained)
#
# Comparison:
# tap: 80 allocated
# join: 329 allocated - 4.11x more
# ruby 2.4.0p0
# Warming up --------------------------------------
# join 83.091k i/100ms
# tap 153.893k i/100ms
# Calculating -------------------------------------
# join 1.127M (± 3.3%) i/s - 5.650M in 5.017113s
# tap 2.918M (± 4.1%) i/s - 14.620M in 5.019061s
#
# Comparison:
# tap: 2917894.7 i/s
# join: 1127426.0 i/s - 2.59x slower
#
# Calculating -------------------------------------
# join 328.000 memsize ( 0.000 retained)
# 5.000 objects ( 0.000 retained)
# 4.000 strings ( 0.000 retained)
# tap 80.000 memsize ( 0.000 retained)
# 2.000 objects ( 0.000 retained)
# 2.000 strings ( 0.000 retained)
#
# Comparison:
# tap: 80 allocated
# join: 328 allocated - 4.10x more
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment