对整个字符串调用一次drawText 与对字符串中的每个字符(或单词)调用一次drawText 之间有显着差异吗?
最佳答案
为了好玩,我为此做了一个测试。我曾认为完整的字符串绘制会更快,主要是因为从 java 到 native 代码的上下文切换次数减少了。结果很有趣。
测试如下。我创建了一个简单的自定义 View ,它扩展了 View 并实现了 onDraw,如下所示:
String text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String t[] = {"A","B","C","D","E","F","G","H","I","J",
"K","L","M","N","O","P","Q","R","S","T",
"U","V","W","X","Y","Z"};
long fulltime=0;
double fullavetime=0;
long fullcount=0;
long chartime=0;
double charavetime=0;
long charcount=0;
@Override
protected void onDraw(Canvas canvas) {
float width = (float) getWidth();
float inc=width/26;
float y1 = (float) getHeight() / 3;
float y2 = y1*2;;
float x=0;
// do this test loop 1000 times to get time data
if (fullcount < 1000) {
// test by char using a simple 26 char string
// I tried to eliminate as much overhead as possible
// so this just pulls strings from an array and draws them
long start=System.currentTimeMillis();
for (int i=0;i<26;i++) {
canvas.drawText(t[i], x, y1, textPaint);
x+=inc;
}
long end=System.currentTimeMillis();
long elapse=end-start;
chartime+=elapse;
charcount++;
charavetime=(double)chartime/charcount;
// draw the entire 26 char string at once
x=0f;
start=System.currentTimeMillis();
canvas.drawText(text, x, y2, textPaint);
end=System.currentTimeMillis();
elapse=end-start;
fulltime+=elapse;
fullcount++;
fullavetime=(double)fulltime/fullcount;
} else {
// after the 1000 test draws, just paint the results on screen
canvas.drawText("bychar "+charavetime, 0, y1, textPaint);
canvas.drawText(" full "+fullavetime, 0, y2, textPaint);
}
// keep painting over and over
invalidate();
}
我在手边的三部手机上运行了这个,这是结果
HTC EVO 4G (2.2)
bychar 1.055 1.142 1.184
full .398 .354 .432
Motorola Droid (2.1 up 1)
bychar .951 1.108 1.071
full .138 .146 .134
Nexus One (2.3.3)
bychar .991 1.033 1.045 .938
full .839 .886 .891 .819
我还做了一个模拟器,它的 bychar 结果是 10x 全字符串结果,结果很滑稽。
结果有些令人惊讶。显然,motorola droid 具有非常快的 native 文本绘制例程,以及同样慢的 java 到 native thunk。
一如既往,仔细检查代码,我可能做了一些扭曲测试的事情。
我的看法是,您应该尽可能绘制完整的字符串。正如他们所说,您的里程可能会有所不同。
关于java - canvas.drawText - 多次与一次开销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5682774/