Skip to content

Instantly share code, notes, and snippets.

@joel
Created July 11, 2012 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joel/3090583 to your computer and use it in GitHub Desktop.
Save joel/3090583 to your computer and use it in GitHub Desktop.
ARRAY.reject! { |c| c.empty? } vs ARRAY.reject!(&:empty?)
require 'benchmark'
N = 10000
ARRAY = begin
[].tap do |array|
(1..1000).to_a.each do |entry|
array << '' if rand(5) == 0
array << entry.to_s
end
end
end
EMPTY_STRING = ''
Benchmark.bmbm do |x|
x.report(".reject!(&:empty?)") { N.times {
ARRAY.reject(&:empty?)
} }
x.report("entry == ''") { N.times {
ARRAY.reject { |entry| entry == EMPTY_STRING }
} }
x.report("|c| c.empty?") { N.times {
ARRAY.reject { |c| c.empty? }
} }
end
# user system total real
# .reject!(&:empty?) 0.960000 0.010000 0.970000 ( 1.205196)
# entry == '' 1.370000 0.000000 1.370000 ( 1.523413)
# |c| c.empty? 1.600000 0.010000 1.610000 ( 1.820435)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment