Created
June 26, 2014 04:01
-
-
Save baweaver/074a4fef30ddca7fe8f6 to your computer and use it in GitHub Desktop.
Only mildly confounded, and the difference is only truly pronounced at larger orders. Given a complicated enough conditional in a block though and this could have a serious effect.
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
[24] pry(main)> def test(range, gt=nil) | |
[24] pry(main)* range.select { |n| gt ? n > gt : n }.reduce(:+) | |
[24] pry(main)* end | |
=> nil | |
[25] pry(main)> def test2(range, gt=nil) | |
[25] pry(main)* filter = gt ? -> n { n > gt } : -> n { n } | |
[25] pry(main)* range.select(&filter).reduce(:+) | |
[25] pry(main)* end | |
=> nil | |
[26] pry(main)> Benchmark.measure { test((1..1_000_000)) }.real | |
=> 0.208830022 | |
[27] pry(main)> Benchmark.measure { test((1..1_000_000),100) }.real | |
=> 0.213170894 | |
[28] pry(main)> Benchmark.measure { test2((1..1_000_000)) }.real | |
=> 0.201729584 | |
[29] pry(main)> Benchmark.measure { test2((1..1_000_000), 100) }.real | |
=> 0.198336247 | |
[31] pry(main)> Benchmark.measure { 100.times { test((1..1_000_000)) } }.real | |
=> 18.096055603 | |
[32] pry(main)> Benchmark.measure { 100.times { test2((1..1_000_000)) } }.real | |
=> 15.557792238 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
What Ruby version are you using to test this?
These are my results:
There's still a difference, but it's less pronounced.