Skip to content

Instantly share code, notes, and snippets.

@baweaver
Created June 26, 2014 04:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baweaver/074a4fef30ddca7fe8f6 to your computer and use it in GitHub Desktop.
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.
[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
@kvannotten
Copy link

What Ruby version are you using to test this?

These are my results:

[4] pry(main)> Benchmark.measure { test((1..1_000_000)) }.real
=> 0.186278
[5] pry(main)> Benchmark.measure { test((1..1_000_000),100) }.real
=> 0.209084
[6] pry(main)> Benchmark.measure { test2((1..1_000_000)) }.real
=> 0.175825
[7] pry(main)> Benchmark.measure { test2((1..1_000_000), 100) }.real
=> 0.179605
[8] pry(main)> Benchmark.measure { 100.times { test((1..1_000_000)) } }.real
=> 18.893062
[9] pry(main)> Benchmark.measure { 100.times { test2((1..1_000_000)) } }.real
=> 17.401746

There's still a difference, but it's less pronounced.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment