Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple TextView.setText causes 40% CPU Usage

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?

like image 802
phlebas Avatar asked May 29 '12 18:05

phlebas


1 Answers

I noticed this myself a while ago, I think the problem is that every time you call setText, the size of the textbox can change, thus requiring the entire screen to go through relayout (expensive).

I haven't tried this myself yet, but if your textbox is simple and can be made to be a relatively fixed size, maybe try to subclass TextView and create a view that does not resize itself on setText, but rather just draws whatever it can into the existing area? That would save a lot of time.

Perhaps theres already a flag to setText that can make it do this, but I'm not aware of it, though I haven't searched closely.

like image 84
Tim Avatar answered Sep 18 '22 23:09

Tim