File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff line change @@ -446,6 +446,26 @@ Calculating -------------------------------------
446
446
Comparison:
447
447
Array#unshift: 44.9 i/s
448
448
Array#insert: 0.2 i/s - 262.56x slower
449
+
450
+ ```
451
+ ##### ` Array#concat ` vs ` Array#+ ` [ code] ( code/array/array-concat-vs-+.rb )
452
+ ` Array#+ ` returns a new array built by concatenating the two arrays together to
453
+ produce a third array. ` Array#concat ` appends the elements of the other array to self.
454
+ This means that the + operator will create a new array each time it is called
455
+ (which is expensive), while concat only appends the new element.
456
+ ```
457
+ $ ruby -v code/array/array-concat-vs-+.rb
458
+ ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin18]
459
+ Warming up --------------------------------------
460
+ Array#concat 23.000 i/100ms
461
+ Array#+ 1.000 i/100ms
462
+ Calculating -------------------------------------
463
+ Array#concat 217.669 (±15.2%) i/s - 1.058k in 5.016952s
464
+ Array#+ 1.475 (± 0.0%) i/s - 8.000 in 5.467642s
465
+
466
+ Comparison:
467
+ Array#concat: 217.7 i/s
468
+ Array#+: 1.5 i/s - 147.54x slower
449
469
```
450
470
451
471
### Enumerable
Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments