Skip to content

Instantly share code, notes, and snippets.

@davydovanton
Last active October 4, 2018 11:14
Show Gist options
  • Save davydovanton/122110ba4afe450a4b0611cfb1910aa4 to your computer and use it in GitHub Desktop.
Save davydovanton/122110ba4afe450a4b0611cfb1910aa4 to your computer and use it in GitHub Desktop.
||= vs unless
require "benchmark/ips"
def fast
test = nil
test = 'test' unless test
test = 'new test' unless test
end
def slow
test = nil
test ||= 'test'
test ||= 'new test'
end
Benchmark.ips do |x|
x.report("fast code description") { fast }
x.report("slow code description") { slow }
x.compare!
end
# Warming up --------------------------------------
# fast code description
# 246.725k i/100ms
# slow code description
# 237.570k i/100ms
# Calculating -------------------------------------
# fast code description
# 6.824M (± 8.4%) i/s - 34.048M in 5.027930s
# slow code description
# 6.475M (± 8.0%) i/s - 32.310M in 5.025982s
#
# Comparison:
# fast code description: 6824482.9 i/s
# slow code description: 6475027.7 i/s - same-ish: difference falls within error
# same but with class and instance variables
require "benchmark/ips"
class Fast
def call
@test = 'test' unless @test
@test = 'new test' unless @test
end
end
class Slow
def call
@test ||= 'test'
@test ||= 'new test'
end
end
Benchmark.ips do |x|
x.report("fast code description") { Fast.new.call }
x.report("slow code description") { Slow.new.call }
x.compare!
end
# Warming up --------------------------------------
# fast code description
# 187.973k i/100ms
# slow code description
# 172.729k i/100ms
# Calculating -------------------------------------
# fast code description
# 4.090M (± 7.3%) i/s - 20.489M in 5.038466s
# slow code description
# 3.606M (± 7.6%) i/s - 17.964M in 5.014272s
#
# Comparison:
# fast code description: 4089680.8 i/s
# slow code description: 3606124.9 i/s - same-ish: difference falls within error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment