Last active
February 15, 2016 12:55
-
-
Save whatthewhat/89350e6051fe2f7c2a9a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark/ips' | |
DATA_POINTS = (1..10000).map { |i| | |
if i > 8000 # 20% | |
{ value: nil } | |
else | |
{ value: 1 } | |
end | |
} | |
module ArrayExtensions | |
refine Array do | |
def drop_right_while_slow | |
self.reverse.drop_while { |el| yield(el) }.reverse | |
end | |
def drop_right_while_fast | |
elements_to_drop = 0 | |
for index in (length - 1).downto(0) | |
if yield(self[index]) | |
elements_to_drop += 1 | |
else | |
break | |
end | |
end | |
last_index = length - elements_to_drop - 1 | |
self[0..last_index] | |
end | |
end | |
end | |
class MyClass | |
using ArrayExtensions | |
def slow | |
DATA_POINTS.drop_right_while_slow { |el| el[:value].nil? } | |
end | |
def fast | |
DATA_POINTS.drop_right_while_fast { |el| el[:value].nil? } | |
end | |
end | |
test = MyClass.new | |
Benchmark.ips do |x| | |
x.report('drop_right_while_slow') { test.slow } | |
x.report('drop_right_while_fast') { test.fast } | |
x.compare! | |
end | |
# => | |
# Calculating ------------------------------------- | |
# drop_right_while_slow 355.000 i/100ms | |
# drop_right_while_fast 352.000 i/100ms | |
# ------------------------------------------------- | |
# drop_right_while_slow 3.721k (± 4.4%) i/s - 18.815k | |
# drop_right_while_fast 3.526k (± 2.4%) i/s - 17.952k | |
# Comparison: | |
# drop_right_while_slow: 3720.9 i/s | |
# drop_right_while_fast: 3526.4 i/s - 1.06x slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment