【发布时间】:2013-05-03 22:55:51
【问题描述】:
我看到了 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 不应该花费任何时间来执行,因此所用时间应该以毫秒为单位,但这是输出
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 版本上尝试过。
【问题讨论】:
-
你是否真的引用了局部变量,所以它的创建没有完全优化?
-
@JoachimIsaksson 我确实尝试在测试方法的开始和结束时打印第一个和最后一个项目,但仍然使用本地变量它很快,即使不是,问题仍然存在 ex.message 是如何受到影响的通过这一切
-
@ScottBartell 这和这有什么关系?