Created
February 11, 2021 10:19
-
-
Save mbajur/8f3bd7ce93a553c6feb672db9989cf08 to your computer and use it in GitHub Desktop.
Ruby `#to_s` vs `|| ''` benchmark
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' | |
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) | |
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' | |
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