Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add comparison for method vs forwarded method vs delegated method #182

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,26 @@ Comparison:
module_eval with string: 1129.7 i/s - 1.19x slower
```

##### Method vs Forwarded method vs Delegated method [code](code/general/method-vs-forwarded-method-vs-delegated-method.rb)

```
$ ruby -v code/general/method-vs-forwarded-method-vs-delegated-method.rb
ruby 2.2.0p0 (2014-12-25 revision 49005) [x86_64-darwin19]
Warming up --------------------------------------
method 247.079k i/100ms
forwarded method 183.323k i/100ms
delegated method 136.666k i/100ms
Calculating -------------------------------------
method 2.481M (± 0.5%) i/s - 12.601M in 5.078755s
forwarded method 1.830M (± 0.8%) i/s - 9.166M in 5.009606s
delegated method 1.365M (± 0.6%) i/s - 6.833M in 5.006191s

Comparison:
method: 2481182.0 i/s
forwarded method: 1829835.8 i/s - 1.36x (± 0.00) slower
delegated method: 1365026.7 i/s - 1.82x (± 0.00) slower
```

##### `raise` vs `E2MM#Raise` for raising (and defining) exeptions [code](code/general/raise-vs-e2mmap.rb)

Ruby's [Exception2MessageMapper module](http://ruby-doc.org/stdlib-2.2.0/libdoc/e2mmap/rdoc/index.html) allows one to define and raise exceptions with predefined messages.
Expand Down
39 changes: 39 additions & 0 deletions code/general/method-vs-forwarded-method-vs-delegated-method.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
require 'benchmark/ips'
require 'forwardable'
require 'delegate'

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