Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to store value as variable or call method again?

Recently, I started learning some Java. From what I've already learned about JVM it looks like JIT makes it pretty fast on operations requiring CPU cycles (i.e. calling a method) but also makes it hungry for memory. So when I need same output from same method as before, is it generally better approach to store the output from before in variable and use it again - while holding it in memory all this time - or call the same method again?

like image 464
Red Avatar asked Aug 01 '10 19:08

Red


1 Answers

It is better practice to hold the output in a variable rather than calling the function again. The variable is going to be held in memory as long as it requires. After that automatic garbage collection will take care of that to free it up from the memory. But if you call the function, it will eat up the memory for its activation record stack each time it gets called. So if you want your program not to be memory hungry, its better to store the result in a variable and use it wherever it is required.

like image 151
Anindya Chatterjee Avatar answered Oct 18 '22 06:10

Anindya Chatterjee