As a developer sometimes we use exceptions as flow control. It could be expensive. I am going to show you how a simple change could help you to save a lot of time by simply not accepting exception as your code flow controller.
In this example, I will throw an exception if required data is not available during execution I will throw an IllegalArgumentException and in another case, I simply return a value using which call is going to take the decision based on the value then we will see how different it will be.
In this example, I will throw an exception if required data is not available during execution I will throw an IllegalArgumentException and in another case, I simply return a value using which call is going to take the decision based on the value then we will see how different it will be.
Code Output
In case of exception, it will take around a minute for execution and in another case it is insignificant. Both methods are invoked one million times to determine the impact.
I request you to think again if you are using exception as your flow controller in a code which will be invoked many times.
Code Output |
Then what if I have to address an exception scenario
If I need to address an exception scenario then for optimization I could pre-allocate the exception object so that I can use them multiple times.Code Output
Let me know your thoughts about it.