With newer compilers I find myself trying to write code that is easier to read but may be more memory hungry if the optimization I hope are being done under the hood are not actually being done.
Take this code for example, very simple case
while (scanner.hasNextLine() && !result)
{
String line = scanner.nextLine();
result = line.indexOf(searchString) >= 0;
}
Would it be fair to assume ( Using Eclipse Juno, Java 7 ) that this will generate the same byte code as
while (scanner.hasNextLine() && !result)
{
result = scanner.nextLine().indexOf(searchString) >= 0;
}
The former although 2 lines of code reduces the length of the second line and makes it easier on the eye. IMHO
But would it also result in an unessecary String object being created? I hope not …
You cannot escape the
Stringbeing created. The fact that you assign it to a local variable is irrelevant here and actually at the bytecode level this fact will not even be noticed: at that level, with or without an explicit variable, the reference to the result must be placed on the stack in order to be passed into the next method invocation in the chain.Your idea that an unnecessary
Stringinstance is created may stem from an instinct coming from another language, such as C: the assignmentString s = ...only copies the reference to the one and only string instance. This is due to the fact that all Java objects reside on the heap, so you always need to explicitly copy an object to actually involve another instance. For example, if you wroteString line = new String(scanner.nextLine()), that would indeed create an unnecessary instance ofString.To conclude, there is no optimization involved in any version of your code, so choose according to stylistic preference only.