Java code optimization, it will optimize this

For newer compilers, I find myself trying to write more readable code, but if the optimization I want to do under the hood is not actually done, I may need more memory

while (scanner.hasNextLine() && !result)
{
    String line = scanner.nextLine();
    result = line.indexOf(searchString) >= 0;
}

Is it fair to assume (using eclipse Juno, Java 7) that this will produce the same bytecode

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 eyes With all due respect, does it also lead to the creation of an unrelated string object? I hope not

Solution

You cannot escape the string being created The fact that it is assigned to a local variable is irrelevant here. In fact, at the bytecode level, this fact will not even be noticed: at this level, whether there is an explicit variable or not, the reference to the result must be placed on the stack in order to be passed to the next method call in the chain

Your idea of creating unnecessary string instances may stem from an instinct from another language, such as C: assign string s =... Copy only references to unique string instances This is because all Java objects reside on the heap, so you always need to explicitly copy the object to actually involve another instance For example, if you write string line = new string (scanner. Nextline()), it does create an unnecessary string instance

In summary, no version of code involves optimization, so please select only according to style preferences

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>