-
Notifications
You must be signed in to change notification settings - Fork 375
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add comparison for method vs forwarded method vs delegated method
- Loading branch information
1 parent
38f49f9
commit 927a17d
Showing
2 changed files
with
58 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
38 changes: 38 additions & 0 deletions
38
code/general/method-vs-forwarded-method-vs-delegated-method.rb
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,38 @@ | ||
require 'benchmark/ips' | ||
require 'forwardable' | ||
|
||
class AdvancedArray < SimpleDelegator | ||
def initialize(*args) | ||
@args = args | ||
self.__setobj__(@args) | ||
end | ||
|
||
def push(value) | ||
@args.push(value) | ||
end | ||
|
||
extend Forwardable | ||
def_delegator :@args, :push, :forwarded_push | ||
end | ||
|
||
def fast | ||
array = AdvancedArray.new | ||
array.push(1) # Simple method call | ||
end | ||
|
||
def slow | ||
array = AdvancedArray.new | ||
array.forwarded_push(1) # Forwarded method call | ||
end | ||
|
||
def slowest | ||
array = AdvancedArray.new | ||
array.pop(1) # Delegated method call | ||
end | ||
|
||
Benchmark.ips do |x| | ||
x.report('method') { fast } | ||
x.report('forwarded method') { slow } | ||
x.report('delegated method') { slowest } | ||
x.compare! | ||
end |