简单TextView.setText导致40%的CPU使用率使用率、简单、TextView、setText

2023-09-13 01:03:26 作者:幼稚园萌小疯

运行我的应用程序会导致〜40%的CPU使用率在我的电话:

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);
         ...

通过注释掉的的setText 的方法,CPU占用率下降到了〜4%的预期水平。该方法将被调用每一秒和不刷新ImageViews,CustomViews ...而不会导致相同的负载过量。 除了CPU使用率的Dalvik只是不断致电报告有关10-1000对象的垃圾收集的的setText()的。

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列出了下面的方法,前5个由它们各自的独家CPU%:

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%) 在顶层(6%)

有没有人能够解释这个?

Has anybody an explanation for this?

推荐答案

我刚才注意到这一点我自己,我认为这个问题是每次你打电话的setText,文本框的大小可以改变,因此需要整个屏幕经过重新布局(昂贵的)。

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).

我还没有尝试过这个自己还没有,但如果你的文本框是简单的,可以被制成一个相对固定的大小,也许尝试TextView的子类,并创建一个视图,不调整本身的setText,而只是借鉴不管它可以到现有的区域?这将节省大量的时间。

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.

也许已经孤单一个标志的setText,可以使其做到这一点,但我没有意识到这一点,虽然我还没有仔细搜查。

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.