tags:

views:

325

answers:

5

I was just wondering which would be cheaper, using a try catch block for index out of bounds or checking 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!

+11  A: 

Hi there.

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.

Cheers. Jas.

Jason Evans
Agreed, try/catch is very expensive vs checking the length parameter on the array. +1
Ioxp
Thanks everyone!
Shaded
+2  A: 

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

R. Bemrose
It might depend on how frequently an exception would be thrown. If you check the length every time but only go out of bounds 1 in every 100,000 times, then is a single exception still more expensive than 100,000 bounds checks?
Eric Petroelje
@Eric Petrolje: Integer comparison is a cheap operation; CPUs can run it as a single operation on one of their ALUs (Arithmetic Logic Units).
R. Bemrose
A: 

Check out this post on the try catch.

Ioxp
A: 

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.

jm
+15  A: 

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.

Eric Lippert