Get the latest tech news
The cost of Go's panic and recover
TL;DR ¶ Some of the wisdom contained in Josh Bloch’s Effective Java book is relevant to Go. panic and recover are best reserved for exceptional circumstances. Reliance on panic and recover can noticeably slow down execution, incurs heap allocations, and precludes inlining. Internal handling of failure cases via panic and recover is tolerable and sometimes beneficial. Abusing Java exceptions for control flow ¶ Even though my Java days are long gone and Go has been my language of predilection for a while, I still occasionally revisit Effective Java, Joshua Bloch’s seminal and award-winning book, and I never fail to rediscover nuggets of wisdom in it.
Bloch opens with the following code snippet, which demonstrates a rather peculiar way of iterating over an array (named range) of objects of some Mountain class so as to invoke their climb method: The recovery mechanism is executed only as part of a function’s state being torn down after an error, which is sufficient to handle catastrophe but requires no extra control structures and, when used well, can result in clean error-handling code. The results are plain to see: ClimbAllPanicRecover is lumberingly slow in comparison to ClimbAll in the case of small enough input slices, for which the cost of panic and recover appears to dominate execution time.
Or read this on Hacker News