Skip to content

Instantly share code, notes, and snippets.

@pioz
Last active November 24, 2017 21:22
Show Gist options
  • Select an option

  • Save pioz/029bda54788a76f012710ada014cf4b6 to your computer and use it in GitHub Desktop.

Select an option

Save pioz/029bda54788a76f012710ada014cf4b6 to your computer and use it in GitHub Desktop.
Benchmark different way to concat strings in Ruby
require 'benchmark/ips'
puts "Ruby #{RUBY_VERSION} at #{Time.now}"
puts
firstname = 'soundarapandian'
middlename = 'rathinasamy'
lastname = 22
Benchmark.ips do |x|
x.report("String concatenation") do |times|
String.new << 'Mr. ' << firstname << middlename << lastname.to_s << ' aka soundar'
end
x.report("String interpolate") do |times|
String.new << "Mr. #{firstname} #{middlename} #{lastname} aka soundar"
end
x.report("Sprintf") do |times|
String.new << sprintf("Mr. %s %s %d aka soundar", firstname, middlename, lastname)
end
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment