ruby catch-throw and efficiency

寵の児 提交于 2019-12-04 08:06:13

In addition to being the "correct" way to get out of control structures, catch-throw is also significantly faster(10 times as fast in my testing). Check out this gist for my code and results.

Jacob Dam

Josh's answer is correct. I want to add more information about catch-throw and raise-rescue.

catch-throw is used for flow control whereas raise-rescue is used for exception/error handling. The different is: backtrace is not needed for catch-throw (flow control). Trust me, the main reason causes raise-rescue runs slow than catch-throw 10 times in Josh's gist is raise-rescue takes a lot time to create backtrace object.

If you want to raise without backtrace, use syntax:

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

Checkout my gist. raise without backtrace is much faster than raise with backtrace.

April 2016 Update:

I've updated my gist:

  • Fixed "break" test
  • Added benchmark tests results for newer ruby version 2.1.8, 2.2.4, 2.3.0
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!