Last active
November 24, 2017 21:22
-
-
Save pioz/029bda54788a76f012710ada014cf4b6 to your computer and use it in GitHub Desktop.
Benchmark different way to concat strings in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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