SsJVasto SsJVasto - 1 year ago 83
C# Question

Try{}Catch optimization?

I have a question about best practices regarding exceptions. This weekend, I was working on my little game, and I found myself wondering if it's best to use IF or a TRY to validate NULL... Here are the two variants of a same function:

This is my code using an IF

//Using IF
void ParseGamePad() {
GamePadData pad = GamePad.GetDate(0);
foreach(var btn in Enum.GetValues(GamePad.BUTTONS)) {
if(myArray.ContainsKey(btn))
if(myArray[btn]!=null)
myArray[btn](); //Execute function reference in array
}
return;
}


Here's what the code is like with a
Try{}Catch


//Using TRY
void ParseGamePad() {
GamePadData pad = GamePad.GetDate(0);
foreach(var btn in Enum.GetValues(GamePad.BUTTONS)) {
try {
myArray[btn](); //Execute function reference in array
} catch(System.Exception e) {
// Nothing to do here
}
}
return;
}


The way I figure it, the
IF
block is quicker than the
TRY
block when the element doesn't exist in the array, whereas the
TRY
is quicker when the element exists, but slower when an Exception is caught.

What would you guys do?

PS: This project is on an embedded system, so CPU and RAM are a factor.

Answer Source

If myArray is a Dictionary as I suspect, you can use TryGetValue.

Catching an exception is not a good solution in this case.

The first option has a (very) slight problem, because you're looking for the item twice, so TryGetValue is what I would use. (If myArray is a Dictionary, then myArray is not a good name.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download