-
Notifications
You must be signed in to change notification settings - Fork 377
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add normal way to apply method to block element versus &method(...)
- Loading branch information
1 parent
da3e53c
commit cf64ab7
Showing
2 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
require "benchmark/ips" | ||
|
||
def do_something(n) | ||
4*n + 2 | ||
end | ||
|
||
def fast | ||
[1, 2, 3].map { |n| do_something(n) } | ||
end | ||
|
||
def slow | ||
[1, 2, 3].map(&method(:do_something)) | ||
end | ||
|
||
Benchmark.ips do |x| | ||
x.report("normal") { fast } | ||
x.report("&method") { slow } | ||
x.compare! | ||
end |
cf64ab7
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Haven't looked at the ruby source for the respected methods but how is this different than
block-vs-to_proc
? (Well,Method#to_proc
returns alambda
andSymbol#to_proc
returns aProc
).I think it's somewhat obvious that
slow
would be slower as the test is comparing a method that calls 3 methods to a method that calls 2.cf64ab7
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is about passing the collection's member to method, and not calling method on the collection's member.
I agree. Also
method(:do_something)
gets an instance ofMethod
class. I think this method object costs a lot, so slower.I added this benchmark because people may use this syntax and think this is faster like the case you mentioned: block-vs-to_proc.