加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby exception.message花费了太多时间

发布时间:2020-12-17 02:21:11 所属栏目:百科 来源:网络整理
导读:我看到 ruby非常有趣和灾难性的行为,请参阅下面的代码 class ExceptionTest def test @result = [0]*500000 begin no_such_method rescue Exception = ex puts "before #{ex.class}" st = Time.now ex.message puts "after #{Time.now-st} #{ex.message}" en
我看到 ruby非常有趣和灾难性的行为,请参阅下面的代码

class ExceptionTest

  def test
    @result = [0]*500000

    begin
      no_such_method
    rescue Exception => ex
      puts "before #{ex.class}"
      st = Time.now
      ex.message
      puts "after #{Time.now-st} #{ex.message}"
    end

  end
end

ExceptionTest.new.test

理想情况下,ex.message不应该花费任何时间来执行,因此所用的时间应该是ms,但这是输出

before NameError
after 0.462443 undefined local variable or method `no_such_method' for #<ExceptionTest:0x007fc74a84e4f0>

如果我将[0] * 500000分配给局部变量而不是实例变量,例如result = [0] * 500000它按预期运行

before NameError
after 2.8e-05 undefined local variable or method `no_such_method' for #<ExceptionTest:0x007ff59204e518>

看起来好像ex.message通过实例变量循环,为什么会这样做,请赐教!

我已经尝试过ruby ruby??-1.9.2-p290,ruby-1.9.1-p376,ruby 2.0.0以及codepad.org上的ruby版本.

编辑:文件错误http://bugs.ruby-lang.org/issues/8366

解决方法

在深入研究 the source之后,我发现NameError#消息首先尝试在你的对象上调用inspect,如果该字符串太长,它会调用to_s.由于它以递归方式检查每个实例变量,因此预计检查需要很长时间. (见 documentation进行检查.)

来自error.c:

d = rb_protect(rb_inspect,obj,&state);
if (state)
  rb_set_errinfo(Qnil);
if (NIL_P(d) || RSTRING_LEN(d) > 65) {
  d = rb_any_to_s(obj);
}
desc = RSTRING_PTR(d);

您可以简化此测试,看看它与异常无关:

class InspectTest
  def initialize
    @result = [0]*500000
  end

  def test
    puts "before"
    st = Time.now
    self.inspect
    puts "after #{Time.now-st}"
  end
end

InspectTest.new.test
#before
#after 0.162566

InspectTest.new.foo
# NoMethodError: undefined method `foo' for #<InspectTest:0x007fd7e317bf20>

e=InspectTest.new.tap {|e| e.instance_variable_set(:@result,0) }
e.foo
# NoMethodError: undefined method `foo' for #<InspectTest:0x007fd7e3184580 @result=0>
e.test
#before
#after 1.5e-05

如果您知道您的类将拥有大量数据并且可能会抛出大量异常,那么理论上可以覆盖#inspect.

class InspectTest
  def inspect
    to_s
  end
end

InspectTest.new.test
#before
#after 1.0e-05

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读