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 @@ -464,6 +464,26 @@ Calculating -------------------------------------
464
464
Comparison:
465
465
Array#unshift: 44.9 i/s
466
466
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
467
487
```
468
488
469
489
##### ` Array#new ` vs ` Fixnum#times + map ` [ code] ( code/array/array-new-vs-fixnum-times-map.rb )
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