开发者

Print integer to canvas fast and without garbage collects

I have a tight game loop in a separate thread where I paint a lot of things on the canvas.

When I paint the score to the canvas I use the following function:

public void clearAndDraw(Canvas canvas, Integer score) {
    canvas.drawText(score.toString(), middleOfScreen, textYPosition, paint);

When I check allocations in ddms I see that .toString not 开发者_如何学Gototally unsurprising allocates a char array on each conversion from an Integer to a String. This array will eventually be claimed by the garbage collect and cause uneven rendering of frames on slow android devices.

Is there a better way of painting integers on a canvas that won't cause new allocations and garbage collects?


Use this simple converter method that reuses the same char[]:

private static void intToChar(char[] array, int input) {
    int i = array.length - 1;
    while (input > 0 && i >= 0) {
        array[i--] = (char) (48 + input % 10);
        input /= 10;
    }
}

Make sure that char[] you pass is big enough for given integer to fit into. Also this assumes ASCII encoding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜