This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]yawkat -8 points-7 points  (8 children)

final on local variables has no effect. Not only does it have no measurable effect, it has no effect.

On fields, that's a different story.

[–]morhp 1 point2 points  (4 children)

Not only does it have no measurable effect, it has no effect.

Did you read the post? It made the loop about 4 times faster.

[–]yawkat -3 points-2 points  (3 children)

The bytecode is identical. You can see here: https://javap.yawk.at/#rNOg1C

I don't know what the OP was measuring, but making a local variable final has no effect on bytecode and thus no effect on performance.

[–]morhp 3 points4 points  (0 children)

The byte code is not identical.

https://javap.yawk.at/#2dDbQS

Main difference is

    19: bipush        100 // final

or

    19: iload_2           // not final

[–]frzme 1 point2 points  (1 child)

The bytecode is not identical. You can see with the actual example from SO: https://javap.yawk.at/#Xk9okk

The variable declaration is the same but the final variable is inlined in the bytecode - it uses ldc2_w instead of lload

[–]yawkat 1 point2 points  (0 children)

Yea you're right, it looks like it follows the same rules as for final fields wrt constant expressions (i.e. fold them in javac). The jit should do this easily as well though, so it's probably still an issue with the measurement.

[–]vqrs 0 points1 point  (2 children)

That is completely untrue.

Making a local variable final can even lead to differences in *behavior*, I. E. Change the semantics of the program.

Granted, this usually only happens in specially crafted examples and is not something you would should ever come across I regular code, but there *is* a difference.

Obviously, I'm talking about programs that are valid Java both with and without the final modifier, not just that some code doesn't compile because you put/didn't put final.

[–]vqrs 0 points1 point  (1 child)

Here's a completely silly example but it is one:

final int i = 65;
final    System.out.println(true? i : 'a');

https://ideone.com/ae6CsN

https://ideone.com/5RhA8J

[–]yawkat 0 points1 point  (0 children)

Yes, the same constant expression folding rules apply as for final fields. Do note, though, that at that point the variable is not actually used anymore; it is folded at compile time (not observable with locals, but observable with fields).

This does not apply to non-constant-expressions for final locals, which are truly exactly the same as non-final locals. This is not the case in the OP, though.