红宝石捕获掷和效率(ruby catch-throw and efficiency)

2019-08-03 00:18发布

catch in Ruby is meant to jump out of deeply nested code. In Java e.g. it is possible to achieve the same with Java's try-catch meant for handling exceptions, it is however considered poor solution and is also very inefficient. In Ruby for handling exceptions we have begin-raise-rescue and I assume it is also to expensive to use it for other tasks.

Is Ruby's catch-throw really a more efficient solution then begin-raise-rescue or are there any other reasons to use it to break nested blocks instead of begin-raise-rescue?

Answer 1:

除了是“正确”的方式来摆脱控制结构, catch-throw也显著快(10倍的速度在我的测试)。 看看这个主旨为我的代码和结果。



Answer 2:

Josh的答案是正确的。 我想加入更多的信息catch-throwraise-rescue

catch-throw用于流量控制而raise-rescue用于异常/错误处理。 不同的是: backtrace不需要用于catch-throw (流量控制)。 相信我,最主要的原因导致raise-rescue的运行不是慢catch-throw 10次在Josh的要点是raise-rescue需要花费大量时间来创建backtrace对象。

如果你想raise无回溯,使用语法:

raise <type>, <message>, <backtrace>

结帐我的要点 。 raise without backtrace比快得多raise with backtrace

2016年4月更新:

我已经更新了我的要点 :

  • 修正了“破发”考验
  • 新增的基准测试结果较新版本的Ruby 2.1.8,2.2.4,2.3.0


文章来源: ruby catch-throw and efficiency