Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require "benchmark/ips"
- class A
- def x; raise "original method not overridden"; end
- def y; raise "original method not overridden"; end
- end
- module AMod
- attr_accessor :x_val, :y_val
- def x; puts x_val end
- def y; puts y_val end
- end
- module BMod
- attr_accessor :x_val, :y_val
- def x
- return super unless x_val
- puts x_val
- end
- def y
- return super unless y_val
- puts y_val
- end
- end
- class B < A
- prepend BMod
- end
- def include_module_at_runtime x_val, y_val
- a = A.new
- a.singleton_class.include AMod
- a.x_val = x_val
- a.y_val = y_val
- a.x
- a.y
- end
- def set_instance_variables x_val, y_val
- a = B.new
- a.x_val = x_val
- a.y_val = y_val
- a.x
- a.y
- end
- def define_module_at_runtime x_val, y_val
- mod = Module.new do
- define_method(:x) { puts x_val }
- define_method(:y) { puts y_val }
- end
- a = A.new
- a.singleton_class.include mod
- a.x
- a.y
- end
- def define_methods_at_runtime x_val, y_val
- a = A.new
- a.define_singleton_method(:x) { puts x_val }
- a.define_singleton_method(:y) { puts y_val }
- a.x
- a.y
- end
- Benchmark.ips do |x|
- %w[include_module_at_runtime set_instance_variables define_module_at_runtime
- define_methods_at_runtime].each do |method|
- x.report(method) do
- send method, 1, 2
- end
- end
- x.compare!
- end
- # Comparison:
- # set_instance_variables: 78453.9 i/s
- # define_methods_at_runtime: 58676.1 i/s - 1.34x slower
- # include_module_at_runtime: 57551.2 i/s - 1.36x slower
- # define_module_at_runtime: 49288.7 i/s - 1.59x slower
Add Comment
Please, Sign In to add comment