File: interceptors.rb

package info (click to toggle)
libneedle-ruby 1.2.0-2
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 1,436 kB
  • ctags: 886
  • sloc: ruby: 4,464; makefile: 52
file content (42 lines) | stat: -rw-r--r-- 1,233 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
$:.unshift "../lib"

require 'benchmark'
require 'needle'

ITERATIONS = 100_000

class TrivialInterceptor
  def initialize( point, parms )
  end

  def process( chain, ctx )
    chain.process_next( ctx )
  end
end

registry = Needle::Registry.new
registry.register( :interceptor ) { TrivialInterceptor }
registry.register( :direct ) { Struct.new( :value ).new }
registry.register( :intercepted_doing ) { Struct.new( :value ).new }
registry.register( :intercepted_with ) { Struct.new( :value ).new }

registry.intercept( :intercepted_doing ).doing { |chain,ctx| chain.process_next(ctx) }
registry.intercept( :intercepted_with ).with { registry.interceptor }

direct = registry.direct
intercepted_doing = registry.intercepted_doing
intercepted_with = registry.intercepted_with

puts
puts "--------------------------------------------------------------------"
puts "Direct method dispatch vs. intercepted method dispatch (trivial)"
puts "#{ITERATIONS} iterations"
puts

Benchmark.bm(20) do |x|
  x.report( "direct:" ) { ITERATIONS.times { direct.value } }
  x.report( "intercepted (doing):" ) { ITERATIONS.times { intercepted_doing.value } }
  x.report( "intercepted (with):" ) { ITERATIONS.times { intercepted_with.value } }
end

puts