开发者

Try-Catch or Check Length?

开发者 https://www.devze.com 2022-12-23 02:59 出处:网络
I was just wondering which would be cheaper, using a try catch block for index out of bounds or checkin开发者_JS百科g the length of a multi dimensional array and comparing values?

I was just wondering which would be cheaper, using a try catch block for index out of bounds or checkin开发者_JS百科g the length of a multi dimensional array and comparing values?

I have a feeling it's the length, since I can store the length in a variable and then just do if's which are relatively cheap. I'm just not sure how expensive try-catch is.

Thanks!


Throwing an exception is extremely expensive compared to checking the value of an integer. However, that's irrelevant. What is more important is that even if exceptions were cheap, they would still be the wrong choice. The point of an exception is that it represents an exceptional occurrance. Exceptions ideally should only be used to represent something unexpected, rare, and preferably fatal.

Another way of looking at it: If you're accessing an array outside its bounds, you have a bug. Fix the bug. An exception handler hides the bug, it doesn't fix the bug.


Checking the length is a much cheaper operation than catching an exception. When you have a try..catch block, it's adding extra structures into your code for catching exceptions - which is fine, I don't say it's wrong, but if you can check the length of the bounds then do that instead.


Throwing an exception is an expensive operation (as you have to generate a stack trace). Go with the length check.


I'd say "measure", if you're wondering which is more efficient for your situation.

For example: What if the out-of-bounds condition is extremely rare? So the out-of-bound never throws... In that case, all that extra "manual" bounds checking could be slower.

CAVEATS: The try/catch would need to be around many out of bounds-checks, so the setup of the try is less significant.

0

精彩评论

暂无评论...
验证码 换一张
取 消