Skip to content

Instantly share code, notes, and snippets.

@wRadion
Last active January 9, 2017 16:10
Show Gist options
  • Save wRadion/c385231f6dbcf73c446cea557ccc3c81 to your computer and use it in GitHub Desktop.
Save wRadion/c385231f6dbcf73c446cea557ccc3c81 to your computer and use it in GitHub Desktop.
Benchmarking Ruby's monkey patch vs alias method vs conventional ways to test Array content.
#! /usr/bin/env ruby
require 'benchmark'
class Array
def blank?
empty?
end
alias :blankk? :empty?
end
class NilClass
def blank?
true
end
alias :blankk? :nil?
end
array = []
10_000_000.times do
case rand(3)
when 0 then array << nil
when 1 then array << []
else array << [*(0..(rand(50)))]
end
end
just = 20
Benchmark.bm do |x|
x.report('with_proc_notation'.ljust(just)) { array.count(&:blankk?) }
x.report('with_alias'.ljust(just)) { array.count { |a| a.blankk? } }
x.report('with_nil?_and_empty?'.ljust(just)) { array.count { |a| a.nil? || a.empty? } }
x.report('with_monkey_patch'.ljust(just)) { array.count { |a| a.blank? } }
x.report('with_just_nil?'.ljust(just)) { array.count { |a| a.nil? || a.count == 0 } }
x.report('with_just_empty?'.ljust(just)) { array.count { |a| a == nil || a.empty? } }
x.report('C-like'.ljust(just)) { array.count { |a| a == nil || a.count == 0 } }
x.report('with_any?'.ljust(just)) { array.count { |a| a == nil || !a.any? } }
end
# RESULT (in seconds, sorted from fastest to slowest)
# user system total real
# with_proc_notation 0.800000 0.000000 0.800000 ( 0.810540)
# with_alias 1.020000 0.000000 1.020000 ( 1.027987)
# with_nil?_and_empty? 1.080000 0.000000 1.080000 ( 1.080706)
# with_monkey_patch 1.180000 0.010000 1.190000 ( 1.183125)
# with_just_nil? 1.270000 0.000000 1.270000 ( 1.278921)
# with_just_empty? 1.510000 0.010000 1.520000 ( 1.510084)
# C-like 1.760000 0.000000 1.760000 ( 1.758057)
# with_any? 2.110000 0.000000 2.110000 ( 2.118271)
#
# with_proc_notation 0.720000 0.010000 0.730000 ( 0.732619)
# with_alias 0.960000 0.000000 0.960000 ( 0.964733)
# with_nil?_and_empty? 1.030000 0.000000 1.030000 ( 1.028848)
# with_monkey_patch 1.080000 0.000000 1.080000 ( 1.083973)
# with_just_nil? 1.230000 0.000000 1.230000 ( 1.248339)
# with_just_empty? 1.480000 0.010000 1.490000 ( 1.486006)
# C-like 1.780000 0.000000 1.780000 ( 1.785834)
# with_any? 2.160000 0.000000 2.160000 ( 2.173112)
#
# with_proc_notation 0.740000 0.000000 0.740000 ( 0.749683)
# with_alias 0.990000 0.000000 0.990000 ( 1.003299)
# with_nil?_and_empty? 1.130000 0.010000 1.140000 ( 1.164617) v
# with_monkey_patch 1.080000 0.010000 1.090000 ( 1.082769) ^
# with_just_nil? 1.270000 0.000000 1.270000 ( 1.288284)
# with_just_empty? 1.510000 0.010000 1.520000 ( 1.514877)
# C-like 1.750000 0.010000 1.760000 ( 1.755909)
# with_any? 2.070000 0.000000 2.070000 ( 2.065673)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment