Skip to content

Commit e594acd

Browse files
authored
Merge pull request #166 from hvenables/combining_arrays
Add Array#concat vs Array#+ Closes issue #165
2 parents 9eb1218 + 16c0779 commit e594acd

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -464,6 +464,26 @@ Calculating -------------------------------------
464464
Comparison:
465465
Array#unshift: 44.9 i/s
466466
Array#insert: 0.2 i/s - 262.56x slower
467+
468+
```
469+
##### `Array#concat` vs `Array#+` [code](code/array/array-concat-vs-+.rb)
470+
`Array#+` returns a new array built by concatenating the two arrays together to
471+
produce a third array. `Array#concat` appends the elements of the other array to self.
472+
This means that the + operator will create a new array each time it is called
473+
(which is expensive), while concat only appends the new element.
474+
```
475+
$ ruby -v code/array/array-concat-vs-+.rb
476+
ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin18]
477+
Warming up --------------------------------------
478+
Array#concat 23.000 i/100ms
479+
Array#+ 1.000 i/100ms
480+
Calculating -------------------------------------
481+
Array#concat 217.669 (±15.2%) i/s - 1.058k in 5.016952s
482+
Array#+ 1.475 (± 0.0%) i/s - 8.000 in 5.467642s
483+
484+
Comparison:
485+
Array#concat: 217.7 i/s
486+
Array#+: 1.5 i/s - 147.54x slower
467487
```
468488

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

code/array/array-concat-vs-+.rb

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

0 commit comments

Comments
 (0)