canvas.drawText - 多次与开销一次

时间:2011-04-15 22:03:13

标签: java android drawtext

在整个字符串上调用drawText一次与为字符串中的每个字符(或单词)调用drawText之间是否存在显着差异?

2 个答案:

答案 0 :(得分:4)

为了好玩,我为此进行了一次测试。我假设完整的字符串绘制速度更快,主要是因为从java到本机代码的上下文切换次数减少。结果很有趣。

测试如下。我创建了一个简单的自定义视图,它扩展了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机器人有一个真正快速的原生文本绘画程序,同样慢的java到本机thunk。

与往常一样,仔细检查代码,我可能做了一些扭曲测试的事情。

我的看法是你应尽可能画出完整的字符串。正如他们所说,你的里程可能会有所不同。

答案 1 :(得分:1)

在字符串中的每个字符上调用drawtext会导致不同设备和屏幕大小的错位。

如果您编写代码来克服该问题,我会假设您当时会跟踪更多变量并调用外部类和方法,这会减慢画布的提取速度。 (如果画布必须在画中画或在课外调用等,它会减慢画布速度)

由于ondraw是一个继承的canvas方法,如果你使用多个实例,它不应该有很多inpact。它背后的所有编码会减慢它的速度