Skip to content

Commit

Permalink
Merge pull request #91 from Drenmi/array-new-vs-fixnum-times-map
Browse files Browse the repository at this point in the history
Add benchmark for Array#new vs. Fixnum#times + map
  • Loading branch information
kindoflew authored Apr 25, 2022
2 parents 38f49f9 + bdfed07 commit 1b4a509
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,25 @@ Comparison:
Array#insert: 0.2 i/s - 262.56x slower
```

##### `Array#new` vs `Fixnum#times + map` [code](code/array/array-new-vs-fixnum-times-map.rb)

Typical slowdown is 40-60% depending on the size of the array. See the corresponding
[pull request](https://github.com/JuanitoFatas/fast-ruby/pull/91/) for performance characteristics.

```
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin15]
Calculating -------------------------------------
Array#new 63.875k i/100ms
Fixnum#times + map 48.010k i/100ms
-------------------------------------------------
Array#new 1.070M (± 2.2%) i/s - 5.365M
Fixnum#times + map 678.097k (± 2.7%) i/s - 3.409M
Comparison:
Array#new: 1069837.0 i/s
Fixnum#times + map: 678097.4 i/s - 1.58x slower
```

### Enumerable

##### `Enumerable#each + push` vs `Enumerable#map` [code](code/enumerable/each-push-vs-map.rb)
Expand Down
17 changes: 17 additions & 0 deletions code/array/array-new-vs-fixnum-times-map.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
require "benchmark/ips"

ELEMENTS = 9

def fast
Array.new(ELEMENTS) { |i| i }
end

def slow
ELEMENTS.times.map { |i| i }
end

Benchmark.ips do |x|
x.report("Array#new") { fast }
x.report("Fixnum#times + map") { slow }
x.compare!
end

0 comments on commit 1b4a509

Please sign in to comment.