I was asked this by a fellow developer recently, and could not provide the answer…
In Java, how/when are variables disposed of? Are they?
Let’s say we have a run() method that gets called 50-75 times per second (heavily simplified example)…
public void run() {
long lastTime = System.nanoTime();
double unprocessed = 0;
int ticks = 0;
int frames = 0;
double nsPerTick = 1000000000.0 / 60.0;
long now = System.nanoTime();
unprocessed += (now - lastTime) / nsPerTick;
lastTime = now;
ticks++;
tick();
unprocessed -= 1;
}
Would bringing those variables (lastTime, unprocessed, ticks, etc.) into a higher level of scope make the program run better/more efficiently–to a place where they are not created and used multiple times per second?
It won’t give you any performance improvement as those variables are created in
stack.Read this article to get more about Object destructions in Java:
What method in Java is used to destroy your objects