Skip to content

Commit 0184134

Browse files
Victor PereiraJuanitoFatas
authored andcommitted
Added benchmark for array#first array#last vs index
- makes title smaller - Fix code example and update README. @JuanitoFatas Closes #32.
1 parent de62e2a commit 0184134

File tree

3 files changed

+70
-0
lines changed

3 files changed

+70
-0
lines changed

README.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,42 @@ Comparison:
158158
Array#shuffle.first: 304341.1 i/s - 18.82x slower
159159
```
160160

161+
##### `Array#[](0)` vs `Array#first` [code](code/array/array_first-vs-index.rb)
162+
163+
```
164+
$ ruby -v code/array/array-first-vs-index.rb
165+
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin14]
166+
167+
Calculating -------------------------------------
168+
Array#[0] 152.751k i/100ms
169+
Array#first 148.088k i/100ms
170+
-------------------------------------------------
171+
Array#[0] 8.614M (± 7.0%) i/s - 42.923M
172+
Array#first 7.465M (±10.7%) i/s - 36.874M
173+
174+
Comparison:
175+
Array#[0]: 8613583.7 i/s
176+
Array#first: 7464526.6 i/s - 1.15x slower
177+
```
178+
179+
##### `Array#[](-1)` vs `Array#last` [code](code/array/array_last-vs-index.rb)
180+
181+
```
182+
$ ruby -v code/array/array-last-vs-index.rb
183+
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin14]
184+
185+
Calculating -------------------------------------
186+
Array#[-1] 151.940k i/100ms
187+
Array#last 153.371k i/100ms
188+
-------------------------------------------------
189+
Array#[-1] 8.582M (± 4.6%) i/s - 42.847M
190+
Array#last 7.639M (± 5.7%) i/s - 38.189M
191+
192+
Comparison:
193+
Array#[-1]: 8582074.3 i/s
194+
Array#last: 7639254.5 i/s - 1.12x slower
195+
```
196+
161197

162198
### Enumerable
163199

code/array/array-first-vs-index.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
require 'benchmark/ips'
2+
3+
ARRAY = [*1..100]
4+
5+
def fast
6+
ARRAY[0]
7+
end
8+
9+
def slow
10+
ARRAY.first
11+
end
12+
13+
Benchmark.ips do |x|
14+
x.report('Array#[0]') { fast }
15+
x.report('Array#first') { slow }
16+
x.compare!
17+
end

code/array/array-last-vs-index.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
require 'benchmark/ips'
2+
3+
ARRAY = [*1..100]
4+
5+
def fast
6+
ARRAY[-1]
7+
end
8+
9+
def slow
10+
ARRAY.last
11+
end
12+
13+
Benchmark.ips do |x|
14+
x.report('Array#[-1]') { fast }
15+
x.report('Array#last') { slow }
16+
x.compare!
17+
end

0 commit comments

Comments
 (0)