Skip to content

Instantly share code, notes, and snippets.

@mbajur
Created February 11, 2021 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbajur/8f3bd7ce93a553c6feb672db9989cf08 to your computer and use it in GitHub Desktop.
Save mbajur/8f3bd7ce93a553c6feb672db9989cf08 to your computer and use it in GitHub Desktop.
Ruby `#to_s` vs `|| ''` benchmark
require 'benchmark'
n = 100_000
Benchmark.bm do |benchmark|
benchmark.report("#to_s") do
n.times do
nil.to_s
end
end
benchmark.report("|| ''") do
n.times do
n || ''
end
end
end
# user system total real
# #to_s 0.010353 0.000055 0.010408 ( 0.016294)
# || '' 0.006720 0.000058 0.006778 ( 0.017595)
require 'benchmark'
n = 100_000
Benchmark.bm do |benchmark|
benchmark.report("#to_s") do
n.times do
'string'.to_s
end
end
benchmark.report("|| ''") do
n.times do
'string' || ''
end
end
end
# user system total real
# #to_s 0.014510 0.000241 0.014751 ( 0.016535)
# || '' 0.011230 0.000124 0.011354 ( 0.016319)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment