Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Data in a Variable vs Inline Arithmetic

Is there any difference between these two code snippets in terms of memory usage and performance/overhead?

final float xPos = (CAMERA_WIDTH / 2) - (mSprite.getWidth() / 2);
final float yPos = (CAMERA_HEIGHT / 2) - (mSprite.getHeight() / 2);
mSprite.setPosition(xPos, yPos);

and the other case:

mSprite.setPosition(((CAMERA_WIDTH / 2) - (mSprite.getWidth() / 2)), ((CAMERA_HEIGHT / 2) - (mSprite.getHeight() / 2)));

The only difference I can see is that the first snippet is storing the variable in what I assume to be a different area of memory than the second snippet, but I'm not very familiar with Java memory allocation (I'm more of a C/C++ person).

My question is: is there any benefit to one way or the other? Does using the final keyword in the first example affect it at all?

Thank you!

like image 240
K. Barresi Avatar asked Oct 25 '12 03:10

K. Barresi


2 Answers

Is there any difference between these two code snippets in terms of memory usage and performance/overhead

I will try to answer the second question. But stand to be corrected.

In case one, two variables get created on the stack , while the function that is being executed is run.

The memory for object mSprite is created in heap memory. And there is no difference in how much memory is allocated for this object in option (1) and (2)

So the only difference between (1) and (2) is that (1) creates more memory on stack. And this is retrieved as soon as method executing this function is exited.

like image 35
smk Avatar answered Oct 07 '22 18:10

smk


Does using the final keyword in the first example affect it at all?

In terms of memory no. But final guarantees that throughout execution reference can't be pointed to some other object in case you are dealing with objects (if primitive types, final guarantees that value for that variable not going to change through out execution)

Is there any difference between these two code snippets in terms of memory usage and performance/overhead

Based on experience I am guessing, of course there will be overhead in first approach, because variable need to be created and maintained (Both cases memory usage would be ALMOST same). Even though there is some overhead, with current computing infrastructure, it would be negligible.

But first approach is more readable and maintainable comparing with second approach. Let us leave micro-optimization to JVM

like image 145
kosa Avatar answered Oct 07 '22 18:10

kosa