Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,27 @@ Enumerable#sort_by (Symbol#to_proc): 25916.1 i/s
Enumerable#sort: 14018.3 i/s - 1.85x slower
```

##### `Enumerable#inject Symbol` vs `Enumerable#inject Proc` [code](code/enumerable/inject-symbol-vs-block.rb)

Of note, `to_proc` for 1.8.7 is considerable slower than the block format

```
$ ruby -v code/enumerable/inject-sum-vs-block.rb
ruby 2.2.4p230 (2015-12-16 revision 53155) [x86_64-darwin14]
Warming up --------------------------------------
inject symbol 1.893k i/100ms
inject to_proc 1.583k i/100ms
inject block 1.390k i/100ms
Calculating -------------------------------------
inject symbol 19.001k (± 3.8%) i/s - 96.543k
inject to_proc 15.958k (± 3.5%) i/s - 80.733k
inject block 14.063k (± 3.9%) i/s - 70.890k

Comparison:
inject symbol: 19001.5 i/s
inject to_proc: 15958.3 i/s - 1.19x slower
inject block: 14063.1 i/s - 1.35x slower
```

### Hash

Expand Down
24 changes: 24 additions & 0 deletions code/enumerable/inject-symbol-vs-block.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
require "rubygems"
require "benchmark/ips"

ARRAY = (1..1000).to_a

def fastest
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think naming the methods after their relative speed is a bit presumptuous. They're subject to change across runtimes and versions. I think it'd be better to name them after the type of operation being performed.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

+1. I was trying to follow the style guide but I agree

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, sorry. I see now that that could be read as an attack. I just meant the convention in general should change, IMHO.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lol. we're good.

ARRAY.inject(:+)
end

def fast
ARRAY.inject(&:+)
end

def slow
ARRAY.inject { |a, i| a + i }
end

Benchmark.ips do |x|
x.report('inject symbol') { fastest }
x.report('inject to_proc') { fast }
x.report('inject block') { slow }

x.compare!
end