Reputation: 2244
I am writing the program, which should be optimized for usage of heap and GC. Based on this I need to create as less objects as possible. So I am wondering if it is a matter for GC if I write the commands in one line?
For example this code creates 2 objects, which are avaliable for GC:
UUID uuid = UUID.randomUUID();
String s = uuid.toString();
What if I rewrite this code in one line, like this:
String s = UUID.randomUUID().toString();
Will the second variant also create 2 objects for GC or only the String object?
Upvotes: 0
Views: 66
Reputation: 198103
There is no difference whatsoever between those two lines as far as the GC (or, really, any part of Java) is concerned.
It's very unusual to need to worry about optimizing for heap. Do you have a program that already works and takes too much heap, or does too much GC? If not, do not worry about it. This is premature optimization which will likely make things worse. Java's GC is really, really good at what it does. If you are not sure about the difference between those two lines, then you should trust Java to be take care of its own memory usage.
Upvotes: 1