File tree Expand file tree Collapse file tree 2 files changed +16
-16
lines changed Expand file tree Collapse file tree 2 files changed +16
-16
lines changed Original file line number Diff line number Diff line change @@ -291,19 +291,19 @@ Comparison:
291291> [ rails/rails #12065 ] ( https://github.com/rails/rails/pull/12065 )
292292
293293```
294- $ ruby -v code/array /each_with_index-vs-while-loop.rb
294+ $ ruby -v code/enumerable /each_with_index-vs-while-loop.rb
295295ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin14]
296296
297297Calculating -------------------------------------
298- each_with_index 11.496k i/100ms
299- While Loop 20.179k i/100ms
298+ each_with_index 13.138k i/100ms
299+ While Loop 23.385k i/100ms
300300-------------------------------------------------
301- each_with_index 128.855k (± 7.5 %) i/s - 643.776k
302- While Loop 242.344k (± 4.5 %) i/s - 1.211M
301+ each_with_index 140.303k (± 5.3 %) i/s - 709.452k
302+ While Loop 276.221k (± 5.3 %) i/s - 1.380M
303303
304304Comparison:
305- While Loop: 242343.6 i/s
306- each_with_index: 128854.9 i/s - 1.88x slower
305+ While Loop: 276221.4 i/s
306+ each_with_index: 140302.7 i/s - 1.97x slower
307307```
308308
309309##### ` Enumerable#map ` ...` Array#flatten ` vs ` Enumerable#flat_map ` [ code] ( code/enumerable/map-flatten-vs-flat_map.rb )
Original file line number Diff line number Diff line change 1- require ' benchmark/ips'
1+ require " benchmark/ips"
22
33ARRAY = [ *1 ..100 ]
44
5- def slow
6- ARRAY . each_with_index do |number , index |
7- number + index
8- end
9- end
10-
115def fast
126 index = 0
137 while index < ARRAY . size
@@ -17,8 +11,14 @@ def fast
1711 ARRAY
1812end
1913
14+ def slow
15+ ARRAY . each_with_index do |number , index |
16+ number + index
17+ end
18+ end
19+
2020Benchmark . ips do |x |
21- x . report ( 'each_with_index' ) { slow }
22- x . report ( 'While Loop' ) { fast }
21+ x . report ( "While Loop" ) { fast }
22+ x . report ( "each_with_index" ) { slow }
2323 x . compare!
2424end
You can’t perform that action at this time.
0 commit comments