Skip to content

Commit 9be00e7

Browse files
committed
Add benchmark for Array#new vs. Fixnum#times + map
When you need to map the result of a block invoked a fixed amount of times, you have an option between: ``` Array.new(n) { ... } ``` and: ``` n.times.map { ... } ``` The latter one is about 60% slower.
1 parent ca29eed commit 9be00e7

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -382,6 +382,22 @@ Comparison:
382382
Array#insert: 0.2 i/s - 262.56x slower
383383
```
384384

385+
##### `Array#new` vs `Fixnum#times + map` [code](code/array/array-new-vs-fixnum-times-map.rb)
386+
387+
```
388+
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin15]
389+
Calculating -------------------------------------
390+
Array#new 63.875k i/100ms
391+
Fixnum#times + map 48.010k i/100ms
392+
-------------------------------------------------
393+
Array#new 1.070M (± 2.2%) i/s - 5.365M
394+
Fixnum#times + map 678.097k (± 2.7%) i/s - 3.409M
395+
396+
Comparison:
397+
Array#new: 1069837.0 i/s
398+
Fixnum#times + map: 678097.4 i/s - 1.58x slower
399+
```
400+
385401
### Enumerable
386402

387403
##### `Enumerable#each + push` vs `Enumerable#map` [code](code/enumerable/each-push-vs-map.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+
ELEMENTS = 9
4+
5+
def fast
6+
Array.new(ELEMENTS) { |i| i }
7+
end
8+
9+
def slow
10+
ELEMENTS.times.map { |i| i }
11+
end
12+
13+
Benchmark.ips do |x|
14+
x.report("Array#new") { fast }
15+
x.report("Fixnum#times + map") { slow }
16+
x.compare!
17+
end

0 commit comments

Comments
 (0)