From 16c0779030f55cc39d543d58bb594e433668ff3f Mon Sep 17 00:00:00 2001 From: Harry Venables Date: Sun, 23 Dec 2018 14:55:15 +0000 Subject: [PATCH] Add Array#concat vs Array#+ --- README.md | 20 ++++++++++++++++++++ code/array/array-concat-vs-+.rb | 19 +++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 code/array/array-concat-vs-+.rb diff --git a/README.md b/README.md index 677a7a9..a016839 100644 --- a/README.md +++ b/README.md @@ -446,6 +446,26 @@ Calculating ------------------------------------- Comparison: Array#unshift: 44.9 i/s Array#insert: 0.2 i/s - 262.56x slower + +``` +##### `Array#concat` vs `Array#+` [code](code/array/array-concat-vs-+.rb) +`Array#+` returns a new array built by concatenating the two arrays together to +produce a third array. `Array#concat` appends the elements of the other array to self. +This means that the + operator will create a new array each time it is called +(which is expensive), while concat only appends the new element. +``` +$ ruby -v code/array/array-concat-vs-+.rb +ruby 2.5.1p57 (2018-03-29 revision 63029) [x86_64-darwin18] +Warming up -------------------------------------- + Array#concat 23.000 i/100ms + Array#+ 1.000 i/100ms +Calculating ------------------------------------- + Array#concat 217.669 (±15.2%) i/s - 1.058k in 5.016952s + Array#+ 1.475 (± 0.0%) i/s - 8.000 in 5.467642s + +Comparison: + Array#concat: 217.7 i/s + Array#+: 1.5 i/s - 147.54x slower ``` ### Enumerable diff --git a/code/array/array-concat-vs-+.rb b/code/array/array-concat-vs-+.rb new file mode 100644 index 0000000..acfc653 --- /dev/null +++ b/code/array/array-concat-vs-+.rb @@ -0,0 +1,19 @@ +require 'benchmark/ips' + +RANGE = (0..10_000).freeze + +def fast + array = [] + RANGE.each { |number| array.concat(Array.new(10, number)) } +end + +def slow + array = [] + RANGE.each { |number| array += Array.new(10, number) } +end + +Benchmark.ips do |x| + x.report('Array#concat') { fast } + x.report('Array#+') { slow } + x.compare! +end