Java will not and can not extract it from the loop.
Any use of the 'new' keyword will always result in a new object being created.
You would be better off using Double.valueOf()
See the javadoc for Double.valueOf(double)
:
"Returns a Double instance representing the specified double value. If a new Double instance is not required, this method should generally be used in preference to the constructor Double(double), as this method is likely to yield significantly better space and time performance by caching frequently requested values."
If you used this method it would return the same object every time, thus reducing the number of objects created and increasing performance.
However, using valueOf
is still not the answer for you!
valueOf
is still a method call, and method calls do not get optimized away. It will call valueOf
every iteration of the loop. Look through your method and count the method calls. Right now it is 6, including hasNext
and new Double
, which is similar to a method call. These will all happen every time, and no java optimization will change that. You are better off refactoring to remove as many method calls as possible from the loop.