Skip to content

Commit 2ab2c75

Browse files
committed
Update each_with_index vs while loop example.
1 parent 973e232 commit 2ab2c75

File tree

2 files changed

+16
-16
lines changed

2 files changed

+16
-16
lines changed

README.md

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff 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
295295
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin14]
296296
297297
Calculating -------------------------------------
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.855k7.5%) i/s - 643.776k
302-
While Loop 242.344k4.5%) i/s - 1.211M
301+
each_with_index 140.303k5.3%) i/s - 709.452k
302+
While Loop 276.221k5.3%) i/s - 1.380M
303303
304304
Comparison:
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)
Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,7 @@
1-
require 'benchmark/ips'
1+
require "benchmark/ips"
22

33
ARRAY = [*1..100]
44

5-
def slow
6-
ARRAY.each_with_index do |number, index|
7-
number + index
8-
end
9-
end
10-
115
def fast
126
index = 0
137
while index < ARRAY.size
@@ -17,8 +11,14 @@ def fast
1711
ARRAY
1812
end
1913

14+
def slow
15+
ARRAY.each_with_index do |number, index|
16+
number + index
17+
end
18+
end
19+
2020
Benchmark.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!
2424
end

0 commit comments

Comments
 (0)