Skip to content

Instantly share code, notes, and snippets.

@cheerfulstoic
Created October 15, 2019 12:02
Show Gist options
  • Save cheerfulstoic/60600f98ec55ad1cb1402f5536ecbfeb to your computer and use it in GitHub Desktop.
Save cheerfulstoic/60600f98ec55ad1cb1402f5536ecbfeb to your computer and use it in GitHub Desktop.
string_concat_test.rb
Warming up --------------------------------------
interpolation 151.958k i/100ms
StringIO << 57.897k i/100ms
StringIO concat 103.750k i/100ms
Calculating -------------------------------------
interpolation 2.482M (± 9.9%) i/s - 9.877M in 4.027092s
StringIO << 45.806B (±33.8%) i/s - 119.834B
StringIO concat 100.679B (±15.4%) i/s - 272.862B
Comparison:
StringIO concat: 100679464490.0 i/s
StringIO <<: 45806087656.3 i/s - 2.20x slower
interpolation: 2482226.0 i/s - 40560.15x slower
(base) [13:58:40] ~/github/fishbrain/rutilus-api
[assume-catches-migrated !?] > ruby ips_test.rb
Warming up --------------------------------------
interpolation 170.913k i/100ms
StringIO << 58.093k i/100ms
String << 119.074k i/100ms
String concat 98.595k i/100ms
Calculating -------------------------------------
interpolation 2.551M (± 6.7%) i/s - 10.255M in 4.040887s
StringIO << 45.450B (±34.4%) i/s - 118.516B
String << 115.444B (±15.8%) i/s - 302.462B
String concat 95.624B (±15.6%) i/s - 259.181B
Comparison:
String <<: 115443957094.8 i/s
String concat: 95623886021.4 i/s - same-ish: difference falls within error
StringIO <<: 45450279262.0 i/s - 2.54x slower
interpolation: 2550683.1 i/s - 45260.02x slower
require 'benchmark/ips'
s1 = "fooo"
s2 = "baaar"
s3 = "baaazzz"
Benchmark.ips do |x|
x.config(:time => 4, :warmup => 1)
x.report("interpolation") do
"heya#{s1}hiya#{s2}hoya#{s3}huya"
end
x.report("StringIO <<") do |times|
StringIO.new.tap do |out|
out << 'heya'
out << s1
out << 'hiya'
out << s2
out << 'hoya'
out << s3
out << 'huya'
end.string
end
x.report("String <<") do |times|
''.tap do |out|
out << 'heya'
out << s1
out << 'hiya'
out << s2
out << 'hoya'
out << s3
out << 'huya'
end
end
x.report("String concat") do |times|
"".tap do |out|
out.concat('heya')
out.concat(s1)
out.concat('hiya')
out.concat(s2)
out.concat('hoya')
out.concat(s3)
out.concat('huya')
end
end
# Compare the iterations per second of the various reports!
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment