Skip to content

Instantly share code, notes, and snippets.

@louismullie
Created January 30, 2012 22:31
Show Gist options
  • Save louismullie/1707218 to your computer and use it in GitHub Desktop.
Save louismullie/1707218 to your computer and use it in GitHub Desktop.
Benchmark: Array.empty? vs. Array.size == 0
require 'benchmark'
Benchmark.bm do |x|
empty = []
not_empty = [:foo, :bar, :baz]
# (size == 0) is faster than empty? for both empty
# and non-empty arrays.
x.report { 1000000.times { empty.size == 0 } }
x.report { 1000000.times { not_empty.size == 0 } }
# user system total real
# 0.100000 0.000000 0.100000 ( 0.098931)
# 0.100000 0.000000 0.100000 ( 0.100634)
x.report { 1000000.times { empty.empty? } }
x.report { 1000000.times { not_empty.empty? } }
# user system total real
# 0.120000 0.000000 0.120000 ( 0.137860)
# 0.130000 0.010000 0.140000 ( 0.129975)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment