Skip to content

Instantly share code, notes, and snippets.

@kbrock
Last active May 30, 2018 14:10
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 kbrock/1d164ae6a5c2bb95babe9825ed908625 to your computer and use it in GitHub Desktop.
Save kbrock/1d164ae6a5c2bb95babe9825ed908625 to your computer and use it in GitHub Desktop.
Comparing Array blank vs empty
ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-darwin16]
nil slower empty slower full slower
x&.empty? 11985357.7 i/s same 11617138.6 i/s same 11247144.5 i/s same
x.blank? 9909235.8 i/s 1.21x 10488507.9 i/s 1.14x 10418916.8 i/s 1.15x
x.nil? || x.empty? 10194622.1 i/s 1.18x 9584369.0 i/s 1.25x 9667811.7 i/s 1.24x
x.try!(:empty?) 5437472.5 i/s 2.20x 3493090.9 i/s 3.43x 3523153.2 i/s 3.40x
x.try(:empty?) 5448509.8 i/s 2.20x 2109368.9 i/s 5.68x 2168337.2 i/s 5.53x
require 'benchmark/ips'
require 'active_support/all'
ANIL=nil
AEMPTY=[]
AFULL=["a"]
Benchmark.ips do |x|
x.report("ANIL.nil empty") { ANIL.nil? || ANIL.empty? }
x.report("ANIL&.empty") { ANIL&.empty? }
x.report("ANIL.try!empty") { ANIL.try!(:empty?) }
x.report("ANIL.tryempty") { ANIL.try(:empty?) }
x.report("ANIL blank") { ANIL.blank? }
x.report("AEMPTY.nil empty") { AEMPTY.nil? || AEMPTY.empty? }
x.report("AEMPTY&.empty") { AEMPTY&.empty? }
x.report("AEMPTY.try!empty") { AEMPTY.try!(:empty?) }
x.report("AEMPTY.tryempty") { AEMPTY.try(:empty?) }
x.report("AEMPTY blank") { AEMPTY.blank? }
x.report("AFULL.nil empty") { AFULL.nil? || AFULL.empty? }
x.report("AFULL&.empty") { AFULL&.empty? }
x.report("AFULL.try!empty") { AFULL.try!(:empty?) }
x.report("AFULL.tryempty") { AFULL.try(:empty?) }
x.report("AFULL blank") { AFULL.blank? }
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment