Last active
June 28, 2016 16:05
-
-
Save cmar/8e947a78470b82899d32 to your computer and use it in GitHub Desktop.
benchmark each_with_object
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
# each_with_index, each_with_object and inject({}) are all %50 slower then #each | |
# simple each with an addition noop | |
[4] pry(main)> puts Benchmark.measure { (1..10_000_000).each { |i| i + 1 } } | |
0.450000 0.000000 0.450000 ( 0.448808) | |
# each_with_index | |
[5] pry(main)> puts Benchmark.measure { (1..10_000_000).each_with_index { |i, index| i + 1 } } | |
0.650000 0.000000 0.650000 ( 0.645812) | |
# each_with_object | |
[6] pry(main)> puts Benchmark.measure { (1..10_000_000).each_with_object({}) { |i, hash| i + 1 } } | |
0.640000 0.000000 0.640000 ( 0.641546) | |
# using inject style | |
[8] pry(main)> puts Benchmark.measure { (1..10_000_000).inject({}) { |hash, i| i + 1 } } | |
0.660000 0.000000 0.660000 ( 0.660929) | |
# using inject style and returning the hash | |
[9] pry(main)> puts Benchmark.measure { (1..10_000_000).inject({}) { |hash, i| i + 1; hash } } | |
0.670000 0.000000 0.670000 ( 0.674742) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment