Skip to content

Instantly share code, notes, and snippets.

@ccocchi
Created January 6, 2015 11:26
Show Gist options
  • Save ccocchi/dbd8c254f9db5a93b277 to your computer and use it in GitHub Desktop.
Save ccocchi/dbd8c254f9db5a93b277 to your computer and use it in GitHub Desktop.
presence? comes at a cost
require 'benchmark/ips'
require 'active_support/core_ext/object/blank'
find_result = nil
result = Benchmark.ips do |x|
x.report('==') do |times|
i = 0
while i < times
1 if find_result == nil
i += 1
end
end
x.report('!') do |times|
i = 0
while i < times
1 if !find_result
i += 1
end
end
x.report('nil?') do |times|
i = 0
while i < times
1 if find_result.nil?
i += 1
end
end
x.report('present?') do |times|
i = 0
while i < times
1 if !find_result.present?
i += 1
end
end
end
Benchmark.compare *result
@ccocchi
Copy link
Author

ccocchi commented Jan 6, 2015

Calculating -------------------------------------
                  ==    114853 i/100ms
                   !    121360 i/100ms
                nil?    114534 i/100ms
            present?    106463 i/100ms
-------------------------------------------------
                  == 33961119.0 (±6.3%) i/s -  168833910 in   4.999349s
                   ! 40137579.4 (±6.8%) i/s -  199273120 in   4.997456s
                nil? 25855563.9 (±7.1%) i/s -  128392614 in   5.000634s
            present? 10784820.4 (±8.0%) i/s -   53550889 in   5.007098s

Comparison:
                   !: 40137579.4 i/s
                  ==: 33961119.0 i/s - 1.18x slower
                nil?: 25855563.9 i/s - 1.55x slower
            present?: 10784820.4 i/s - 3.72x slower

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment