There are many immutable classes in Java like String
and primitive wrapper classes, and Kotlin introduced many others like Range
subclasses and immutable Collection
subclasses.
For iterating Range
s, from Control Flow: if, when, for, while - Kotlin Programming Language we already know:
A
for
loop over a range or an array is compiled to an index-based loop that does not create an iterator object.
However in other scenarios when dealing with Range
s this optimization is not possible.
When creating such immutable classes with const parameters, or more generally, recursively with const parameters, instantiating the class only once will bring performance gains. (In other words, if we call this a const immutable instantiation, an instantiation is a const immutable instantiation if and only if all its parameters are either constants or const immutable instantiations.) Since the Java compiler doesn't have a mechanism to know whether a class is immutable, does the Kotlin compiler optimize such classes to be instantiated only once, based on its knowledge of its known immutable classes?
For a more specific example of application, consider the following code:
repeat(1024) {
doSomething(('a'..'z').random())
}
val LOWERCASE_ALPHABETS = 'a'..'z'
repeat(1024) {
doSomething(LOWERCASE_ALPHABETS.random())
}
Would the second one bring any performance improvements?