2

I have a large 3d array of data that I will be reading and writing to randomly. By design, approximately 5% of these operations will fall outside the bounds of this array and will be handled differently. Is this an appropriate place to use a try/catch block? Otherwise, I need 6 individual 'if' statements to check the addresses against the array bounds.

Perhaps I am trying to micro-optimize here, but these operations may be happening tens of thousands of times per second. In addition, it would make for slightly cleaner code. I'm using C# here, but I imagine this is a language-independent question.

Camander
  • 147
  • 1
  • 10

1 Answers1

3

Interestingly enough, your question is not language independent on the one hand.

In languages such as C, Java, C++, C# ... people prefer the "LBYL" (Look Before You Leap) pattern; whereas languages such as python heavily emphasize "EAFP" (it's Easier to Ask Forgiveness than Permission).

Meaning: in python, you are using try/catch a lot (even the "counting for loop" is implemented as try/catch); whereas in C# you would prefer doing if/else instead.

And these conventions are really important to follow - most Cx-language programmers simply assume that you don't use try/catch to model control flow.

But coming back to your core requirements: go for if/else. As you are pointing out that performance very well might be an issue; you simply want to avoid the more expensive try/catch solution.

And as said; as nice side effect of doing so, your code will be "more mainstream"; thus readers of your code won't give you to many WTFs per minute.

code quality by WTFs per minute

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Thanks for the quick response, that's very interesting. Is this simply by convention? Or is there actually a significant performance benefit on either side? – Camander Sep 15 '16 at 04:41
  • I was updating my answer in the meantime addressing that part, too. Yes performance matters here. – GhostCat Sep 15 '16 at 04:42