You asked: "... is there a performance optimization that the compiler applies when we use constants instead of variables?"
Answer: yes, absolutely.
Mutated collections can be organized differently than immutable collections so that they can be changed. Immutable collections can be optimized for read-only work.
Then the use of mutable / immutable objects is used. The compiler may need to generate code that copies the modified object when it is shared as a property of another object in order to avoid unwanted side effects.
Comparison of immutable objects (equivalent / comparable) can also be optimized so that mutable objects cannot.
The sultan compiler intelligence question is good. The compiler can often infer that the variable will never change from code analysis, which can lead to comparative testing, allowing the use of vs. var.
Duncan c
source share