Created
November 29, 2013 12:58
-
-
Save cnocon/7705368 to your computer and use it in GitHub Desktop.
Another look at why it's important to understand what the method you are using is returning and how it works. There are some significant advantages and disadvantages to methods that might generate the same, correct, output for you.
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' | |
array = (1..900_000).to_a | |
Benchmark.bmbm do |x| | |
#reject returns the array without the rejected number, so it has to re-index it without the rejected number | |
x.report("reject 890,000") { array.reject{|num| num == 890_000}} | |
x.report("reject 2") { array.dup.reject{|num| num == 2}} | |
#select goes through whole array no matter what bc it returns all matched elements | |
x.report("select 890,000") { array.select{|num| num == 890_000}} | |
x.report("select 2") { array.select{|num| num == 2}} | |
#detect returns the first match for what's in the block, so the later the match, the longer it will take | |
x.report("detect 890,000") { array.detect{|num| num == 890_000}} | |
x.report("detect 2") { array.detect{|num| num == 2}} | |
end | |
=begin | |
# TERMINAL OUTPUT (reordered by speed) | |
user system total real | |
detect 2 0.000000 0.000000 0.000000 ( 0.000007) | |
select 2 0.060000 0.000000 0.060000 ( 0.055447) | |
select 890,000 0.060000 0.000000 0.060000 ( 0.055771) | |
reject 2 0.060000 0.000000 0.060000 ( 0.074060) | |
reject 890,000 0.070000 0.010000 0.080000 ( 0.074298) | |
detect 890,000 0.080000 0.000000 0.080000 ( 0.078985) | |
=end | |
array = (1..900_000).to_a | |
Benchmark.bmbm do |x| | |
x.report("reject 890,000") { array.reject{|num| num == 890_000}} | |
x.report("select 890,000") { array.select{|num| num == 890_000}} | |
x.report("detect 890,000") { array.detect{|num| num == 890_000}} | |
x.report("reject 2") { array.dup.reject{|num| num == 2}} | |
x.report("select 2") { array.select{|num| num == 2}} | |
x.report("detect 2") { array.detect{|num| num == 2}} | |
end | |
=begin | |
# TERMINAL OUTPUT (reordered by speed and num val) | |
user system total real | |
select 890,000 0.060000 0.000000 0.060000 ( 0.055352) | |
reject 890,000 0.070000 0.000000 0.070000 ( 0.072121) | |
detect 890,000 0.080000 0.000000 0.080000 ( 0.079082) | |
detect 2 0.000000 0.000000 0.000000 ( 0.000007) | |
select 2 0.050000 0.000000 0.050000 ( 0.054411) | |
reject 2 0.070000 0.000000 0.070000 ( 0.071456) | |
=end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment