Running my application causes ~40% CPU usage on my Phone:
final String position = String.format("%02d:%02d:%02d", time.getHours(), time.getMinutes(),
time.getSeconds());
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
c.mTxtPosition.setText(position);
...
By commenting out the setText method the CPU Usage drops to the expected level of ~4%. The method is invoked every second and does refresh ImageViews, CustomViews ... without causing the same load excess. Besides the CPU Usage dalvik constantly reports garbage collecting of about 10-1000 objects just by calling setText().
Creating a tracefile like this:
Debug.startMethodTracing("setText");
c.mTxtPosition.setText(position);
Debug.stopMethodTracing();
traceview lists the following methods as Top 5 by their respective exclusive CPU%:
- ViewParent.invalidateChildInParent(16%)
- View.requestLayout(11%)
- ViewGroup.invalidateChild(9%)
- TextView.setText(7%)
- toplevel(6%)
Has anybody an explanation for this?
setText()
, or do you mean commenting out theString.format()
call?String.format()
is expensive. – CommonsWarefinal String position = String.format(...);
withfinal String position = "Hi, Mom!";
and see what happens. It is possible that some compiler optimizations are delaying theformat()
call until you use theposition
variable for the first time. I wouldn't expect this, but it makes more sense than one randomsetText()
call being dramatically more expensive than other things that you are doing. Also, you might consider using Traceview to get more precise information on where the time is being taken up. – CommonsWaresetText()
call should dramatically highlight something if your CPU utilization values are accurate. – CommonsWare