安卓:显示比分的画布上一个字符串创建每个抽奖命令一个新的字符串。我该如何解决这个问题? [英] Android : Displaying score as a string on canvas is creating a new string per draw command. How do I get around this?

查看:100
本文介绍了安卓:显示比分的画布上一个字符串创建每个抽奖命令一个新的字符串。我该如何解决这个问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做一个游戏,显示画布(分数,时间等)上的一些数字。

I'm making a game that displays some numbers on a canvas (score, time, etc).

这是我目前做到这一点的方法是使用DrawText的命令在画布上

The way that I currently do this is with the drawtext command on a canvas

// score is some int
draw(Canvas c) {
    c.drawText(score+"", x, y, paintSyle);
}

我听说对象创建和垃圾收集是昂贵的操作,我想这是每一个被调用时创建一个新的字符串。

I hear that object creation and garbage collection are expensive operations, and I think this is creating a new string every time it is called.

现在我的所有的位图绘制和一切游戏跳跃周围25至60帧。我想它更贴近人数较多,我试图找到方法来加快速度。

Right now my game with all bitmap drawing and everything jumps around from 25 to 60 fps. I'd like it to stay closer to the higher number and I'm trying to find ways to speed it up.

难道是更快/更明智(或找?)字符串,并解决此问题的一些可变的子类?有另一种方式来解决这个问题?还是这只是它是如何?

Would it be faster/better to make(or find?) some mutable subclass of string and work around this problem? Is there another way to solve this issue? Or is this just how it is?

推荐答案

引入了两个新的私人成员变量字符串renderedScoreString INT rederedScore 和重写你的画() -method这样的:

Introduce two new private member variables String renderedScoreString and int rederedScore and rewrite your draw()-method like that:

draw(Canvas c) {
    if (this.score != this.renderedScore || this.renderedScoreString == null) {
        this.renderedScore = this.score;
        this.renderedScoreString = Integer.toString(this.renderedScore);
    }
    c.drawText(this.renderedScore, x, y, paintStyle);
}

这应该为你节省很多!对象的创作。你也可以躲在一个getter方法​​样板code,例如字符串getScoreString()这不一样的,所以你不要有它在画() -method。

that should save you a lot! of object creations. You could also hide the boilerplate code behind a getter method, e.g. String getScoreString() which does the same, so you don't have it in the draw()-method.

这篇关于安卓:显示比分的画布上一个字符串创建每个抽奖命令一个新的字符串。我该如何解决这个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆