Reputation: 2149
My situation is I have a small javascript program running on a huge amount of data formatted as a 2 dimensions array. For every cycle, it loops through the data, calls a serializer method to serialize that record before doing the calculations. The data for every cycle will be the same. So now I want to cache the serialized data into another array so that from the second time it doesn't have to call serializer again.
Here is my function:
var cached=[];
function getRow(x,y){
if(!cached[x]){
cached[x] = [];
}
if(!cached[x][y]){
cached[x][y] = serializer(data,x,y);
}
return cached[x][y] ;
}
So far it works. But as you can see, for every row it must check 2 conditions before returning cached data and the condition only helpful in the first cycle. So I'm thinking about using try-catch instead of if-else to handle it. So that in the first cycle, the try
block will fail all the time then I will fill up the cache in catch
block. Then after the first cycle when all the data has been cached, it will just get the value right the way and return it.
But my concern is: is it faster by doing that or try-catch will slow down the function and the performance just the same?
Upvotes: 0
Views: 517
Reputation: 65806
try/catch
is only going to be more efficient in situations where no error is thrown. And, let's be clear, with modern clients, the increase in efficiency is going to be marginal and probably not noticeable in most applications.
When errors are thrown, performance will suffer because an error object is instantiated and configured, a scope is created for that error object to exist within and (of course) the JS runtime has to recover from the error.
In my experience, try/catch
is generally used incorrectly in the first place. It should not be a matter of "choice" to use try/catch
, it should be a matter or necessity. If there is a chance your code can cause an error and there is a way for you to code it to avoid that error, do that - - no try/catch
needed.
Examples:
If there is a way for your code to throw an error and it is beyond the control of your code (network outage, server error), try/catch
may be necessary. I say may because many APIs these days have error callback functions to handle these kinds of things.
In short, you should never just choose try/catch
. try/catch
is a language feature to be used when no other solution is available.
Upvotes: 4