Ruby 动态方法和幽灵方法的简单 benchmark

flowerwrong · 2015年03月09日 · 最后由 huopo125 回复于 2015年03月10日 · 2230 次阅读

我自己测了一下,有点超乎我的预计,呵呵,不过 Ruby 追求的不是性能

class EntryNormal
  def e_0;end
  def e_1;end
  def e_2;end
  def e_3;end
  def e_4;end
end

class EntryNormal2
  def e_0(x);x;end
  def e_1(x);x;end
  def e_2(x);x;end
  def e_3(x);x;end
  def e_4(x);x;end
end

class Entry
  5.times do |i|
    define_method("e_#{i}"){}
  end
end

class Entry2
  def initialize(n)
    n.times do |i|
      Entry2.define_component("e_#{i}")
    end
  end

  def self.define_component(name)
    define_method(name) do |x|
      x
    end
  end
end

class Entry3
  def method_missing(method, arg)
    arg
  end
end

require 'benchmark/ips'

Benchmark.ips do |x|
  x.report("normal method") do
    en = EntryNormal.new
    en.e_0
    en.e_1
    en.e_2
    en.e_3
    en.e_4
  end

  x.report("normal method args") do
    e = EntryNormal2.new
    e.e_0(1)
    e.e_1(2)
    e.e_2(3)
    e.e_3(4)
    e.e_4(5)
  end

  x.report("method_missing") do
    e = Entry3.new
    e.e_0(1)
    e.e_1(2)
    e.e_2(3)
    e.e_3(4)
    e.e_4(5)
  end

  x.report("dynamic method") do
    e = Entry.new
    e.e_0
    e.e_1
    e.e_2
    e.e_3
    e.e_4
  end

  x.report("dynamic method args") do
    e = Entry2.new(5)
    e.e_0(1)
    e.e_1(2)
    e.e_2(3)
    e.e_3(4)
    e.e_4(5)
  end

  x.compare!
end

Result:

Calculating -------------------------------------
       normal method    64.900k i/100ms
  normal method args    63.045k i/100ms
      method_missing    57.231k i/100ms
      dynamic method    56.053k i/100ms
 dynamic method args     5.584k i/100ms
-------------------------------------------------
       normal method      2.084M (±10.7%) i/s -     10.319M
  normal method args      1.801M (±11.1%) i/s -      8.889M
      method_missing      1.495M (±13.5%) i/s -      7.326M
      dynamic method      1.245M (±13.1%) i/s -      6.110M
 dynamic method args     57.401k (±13.6%) i/s -    284.784k

Comparison:
       normal method:  2084278.1 i/s
  normal method args:  1801098.3 i/s - 1.16x slower
      method_missing:  1494748.3 i/s - 1.39x slower
      dynamic method:  1244953.5 i/s - 1.67x slower
 dynamic method args:    57401.2 i/s - 36.31x slower

[Finished in 35.4s]
需要 登录 后方可回复, 如果你还没有账号请 注册新账号