Re: function call efficiency
I am using a function in Java with return type Array
int out = new int;
Is it efficient way if I have to call this function 1000's of time. Or
I can use out variable as a array variable
public int out = new int;
Which of the two methods will be faster. Or is there any other way to
make it faster.
As Oliver has pointed out, the second option is illegal.
In general terms, I believe what you are asking is, should i be
creating a new object every time my method is called or declare my
object in a class field and reuse it.
Tend toward to former for several reasons...
1) Dont optimize prematurely! Do what is easiest to read and
understand, optimize when you know there is a problem! Making
assumptions about optimization and doing it as you go is only going to
leave you with hard to read code. You will save yourself 1ms at at
runtime with the cost of hours of picking through 'optimized code' at
development time. Its not worth it!
2) Objects created within the scope of a method are inherantly
thread-safe as they are private to the method call which is private to
a thread stack. Trying to share an object may lead to bizarre threading
problems, requiring you to either move back to method level creation,
or synchronization (which will affect performance far far more!).
3) Recent articles I have read have suggested that creating an object
many times within a method is actually MORE efficient than sharing a
single object instance(provided that construction is relatively fast,
which it will be in this case). The reason for this is that the garbage
collector treats short lived objects and long lived objects very
differently and cutting down on long lived objects will result in less
time scanning heap space.