After reading several articles on how to fine-tuning my code, I found out that the way we are declaring objects and variables could drasticatly impact the performance of our application. This is more and more important as time constraint is now an integral part of some aspects of the Android platform (e.g. result must be provided within 5 sec for some operations).
Now, I found the following code in one of my fragment class (perfectly functional):
Activity myA = getActivity();
if(myA instanceof MainActivity) {
((MainActivity) myA).doNext();
}
Knowing that objects creation/destruction and ressources allocation are some of the factors contributing to drain-out the device’s batteries, I had in mind to rewrite my code to:
if(getActivity() instanceof MainActivity) {
((MainActivity ) getActivity()).doNext();
}
From a functional perspective, both codes are delivering the same results. However, what is the most suitable approach? I’m asking because I see pros and cons to both approach and I’m unable to find the appropriate way to evaluate the performance and I’m also not clear on which counters (memory usage, function’ speed, used CPU cycles, etc) the evaluation should be performed.
Thanks for your contribution in advance.
Guessing what could be a performance bottleneck is a very common waste of time. You have to measure what makes a difference to your whole program instead of guessing.
Creating a few objects doesn’t matter. Creating too many object matters. How much is too much and which objects are created most is something you should use a profiler to determine.
Whatever you feel is the simplest. I believe that adding the method
doNextto the class whichgetActivity()returns would be best so you can write the following is clearest.Use a CPU and memory profiler, or write a performance test for different components of your system.
If you can’t use a profiler, I would start simple with elapse time. i.e. System.nanoTime(). This is usually all you need.