mrQWERTY
mrQWERTY

Reputation: 4149

Handler postDelay() new Runnables create garbage?

I've been thinking about implementing postDelay() in my game animation to make it more smooth. What I am worried about is that postDelay() creates a new Runnable everytime it is executed. Since my game needs postDelay() to be executed very often, will this create a lot of garbage since it is creating a new Runnable every time? Or even if it does not, does the creation of a new Runnable slow down performance?

So in this case, is it appropriate to use postDelay() in a situation where it is going to be executed very often for a long time?

Upvotes: 0

Views: 342

Answers (2)

Igor Gorjanc
Igor Gorjanc

Reputation: 555

There's no need to create a new runnanable each time postDely() is executed

private static int LOOP_TIME = 5000;
private Handler handlerWork;

private Runnable runnableWork = new Runnable() {
    @Override
    public void run() {
        //do some work
        handlerWork.postDelayed(runnableWork, LOOP_TIME);
    }
}

@Override
protected void onResume() {
    super.onResume();
    if (handlerWork == null)
        handlerWork = new Handler();
    handlerWork.postDelayed(runnableWork, LOOP_TIME);
}

@Override
protected void onPause() {
    super.onPause();
    if (handlerWork != null)
        handlerWork.removeCallbacks(runnableWork);
}

Upvotes: 1

Mixaz
Mixaz

Reputation: 4178

You can use single Runnable instance for all postDelayed calls.

But I think that a loop is better for games, it's a standard pattern, like in this post: How to appear and disappear an object on screen using game loop for every five second

Upvotes: 1

Related Questions