how to know the performance of part of code using android studio

637 Views Asked by At

I want to know the performance of little fragment of my code using android studio. I am writing a small part of my code here to explain my question

params.rightMargin = (int) (getResources().getDimensionPixelOffset(R.dimen.rightAndLeftMargin));
params.leftMargin = (int) (getResources().getDimensionPixelOffset(R.dimen.rightAndLeftMargin));

alternatively these lines can also be written as:

int margin = getResources().getDimensionPixelOffset(R.dimen.rightAndLeftMargin);
params.rightMargin = margin;
params.leftMargin = margin;

so with the help of android studio IDE how to compare the performance(like memory uses, CPU load, execution time etc.) of these two codes.

NOTE: This is not the only case I have dozens of same cases therefore I would like to have general solution for all types of codes.

2

There are 2 best solutions below

0
Patryk Goworowski On BEST ANSWER

With Profiler built-in into Android Studio you can easily see what methods on what threads are being called in a selected time frame. Personally I recommend using a Flame Chart to see what operation takes most amount of time.

Keep in mind that having a profiler attached to your app's process slows it down significantly, so if certain method call took e.g. 1 second, in reality it will be way less.

0
Tomer Shetah On

I don't know android at all. But when writing code, and you have a computation to make, it is better to make it once, and reuse the result. In your example, the latter is better.

I assume that the resources are already in the memory of the process, so probably the footprint here is minor. It will be to create a new method in the stack for getReaources, and another one for getDimensionPixelOffset. Creating a local variable it much cheaper that that.

The footprint increases significantly if you are making IO operations, such as accessing files, or http actions. In those cases it is much better to declare a local variable and reuse it.