Try-catch or check length?

I'm just wondering what would be cheaper by using a catch try block for an index outside or by checking the length of a multidimensional array and comparing the values?

I have a feeling that this is length, as I can store the length in a variable and then just do it if they are relatively cheap. I just don't know how expensive the attempt is.

Thanks!

+4
source share
4 answers

Length checking is a much cheaper operation than catching an exception. When you have a try..catch block, it adds redundant structures to your code to detect exceptions - this is normal, I'm not saying that this is wrong, but if you can check the length of the borders, then do it instead.

+11
source

Throwing an exception is extremely expensive compared to checking the value of an integer. However, this does not matter. More importantly, even if the exceptions were cheap, they would still be the wrong choice. The exception is that it is an exceptional event. Exceptions should ideally be used only to represent something unexpected, rare, and preferably fatal.

Another way to look at this: if you are accessing an array beyond its borders, you have an error. Correct the mistake. The exception handler hides the error; it does not fix the error.

+19
source

Throwing an exception is an expensive operation (since you need to create a stack trace). Go with a length check.

+2
source

I would say β€œmeasure” if you are interested in what is more effective for your situation.

For example: what if the condition outside is extremely rare? Thus, out-of-bound never throws ... In this case, all unnecessary "manual" border checks can be slower.

CAVEATS: try / catch should be around many extraordinary checks, so the try setting is less significant.

0
source

Source: https://habr.com/ru/post/1304463/


All Articles