From 9be00e7f369e9f6fdcce246d4d3b8b74e4e2e4df Mon Sep 17 00:00:00 2001 From: Ted Johansson Date: Mon, 11 Jan 2016 18:34:58 +0800 Subject: [PATCH 1/2] Add benchmark for Array#new vs. Fixnum#times + map When you need to map the result of a block invoked a fixed amount of times, you have an option between: ``` Array.new(n) { ... } ``` and: ``` n.times.map { ... } ``` The latter one is about 60% slower. --- README.md | 16 ++++++++++++++++ code/array/array-new-vs-fixnum-times-map.rb | 17 +++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 code/array/array-new-vs-fixnum-times-map.rb diff --git a/README.md b/README.md index b1f393f..c172f65 100644 --- a/README.md +++ b/README.md @@ -382,6 +382,22 @@ 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) + +``` +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) diff --git a/code/array/array-new-vs-fixnum-times-map.rb b/code/array/array-new-vs-fixnum-times-map.rb new file mode 100644 index 0000000..fcd7260 --- /dev/null +++ b/code/array/array-new-vs-fixnum-times-map.rb @@ -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 From bdfed07e71883444bbde0c34b3578edf80e34081 Mon Sep 17 00:00:00 2001 From: Ted Johansson Date: Tue, 12 Jan 2016 11:59:22 +0800 Subject: [PATCH 2/2] Add link to benchmark PR in README As suggested by @deniskorobicyn, adding a link from the `README.md` to the PR, which has more information on performance characteristics. --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index c172f65..dba76ed 100644 --- a/README.md +++ b/README.md @@ -384,6 +384,9 @@ Comparison: ##### `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 -------------------------------------