This question already has an answer here:
- if-condition vs exception handler 5 answers
I'm trying to both learn more about the implications of various design choices, and find the most performant solution for preventing errors in my code. Before diving in, allow me to briefly and generally state my question:
Is a try catch block a more efficient solution to handling an out of bounds exception when compared to and if-statement structure?
I understand that raising exceptions is expensive, but is that cost mitigated by removing unnecessary if-statements?
And now, allow me to state my specific issue to give you more useful information.
I'm building a game, and part of that game is a world-grid solution coupled with a pathfinder. Game Units may request nodes from the world-grid, (by sending coordinate information as an ordered pair (x, z)), to then send to the pathfinder or perform on them some other miscellaneous action. Because nodes are being requested with a large amount of frequency, especially by the pathfinder, this seems like a smart place to try to optimize.
Here is my current code for returning a given node based on its x and z values in the array of nodes:
public Node GetTile(int x, int z)
{
if (x < 0)
x = 0;
if (x >= length_X)
x = length_X - 1;
if (z < 0)
z = 0;
if (z >= length_Z)
z = length_Z - 1;
return tiles [x, z];
}
As you can plainly see, I have several if statements in place to avoid out of bounds exceptions when retrieving a node from world-grid's array of nodes(tiles). Is this the most efficient solution? Could I remove the if's and instead place the return in a try catch block like so:
public Node GetTile(int x, int z)
{
try
{
return tiles[x, z];
}
catch (System.IndexOutOfRangeException e)
{
//handle exception here
//do smart programming fix-y stuff
}
}
This solution works, but is there some reason that I'm not aware of that makes it less efficient? My logic for believing it to be a smarter solution is that I'm removing up to four comparisons every single time the method is called. Considering the circumstances under which the program will actually send in values out side of the bounds are rare, this seems like a good trade off. What I don't know though, is how exceptions work behind the scenes. Will checking for an exception be just as expensive as checking the values manually?
Aucun commentaire:
Enregistrer un commentaire