Skip to content

Instantly share code, notes, and snippets.

@davydovanton
Last active April 12, 2021 09:25
Show Gist options
  • Save davydovanton/948934dd69856ae1c766 to your computer and use it in GitHub Desktop.
Save davydovanton/948934dd69856ae1c766 to your computer and use it in GitHub Desktop.
Ruby string interpolation benchmark
require 'benchmark'
first = 'first'
second = 'second'
n = 1_000_000
Benchmark.bm do |x|
x.report('string interpolation: '){ n.times { "#{first}_#{second}" } }
x.report('string interpolation #2: '){ n.times { first + '_' + second } }
x.report('string interpolation #3: '){ n.times { "%s_%s" % [first, second] } }
x.report('join array: '){ n.times { [first, second].join('_') } }
end
# Result:
#
# user system total real
# string interpolation: 0.260000 0.000000 0.260000 ( 0.259696)
# string interpolation #2: 0.280000 0.000000 0.280000 ( 0.282402)
# string interpolation #3: 0.960000 0.000000 0.960000 ( 0.963318)
# join array: 0.680000 0.010000 0.690000 ( 0.678449)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment