how much should I care about putting constant stri...
# compiler
p
how much should I care about putting constant strings into companion objects?
Copy code
// A
fun example() = "banana"

// B
companion object { 
    const val X = "banana"
}
fun example() = X
I guess benefit is storing variable to heap. But on the other hand, I think that adding single-use constants impacts code readability. Any thoughts?
f
Using single-use constants all over the place increases mental load because you need to navigate all around, and cannot know if they are single-use or not without searching. The danger is when a single-use needs another use, since it could be forgotten to update the previously single place where the value was used.
e
the only concern should be readability/maintainability. there is no runtime impact, either way it will compile to a load from the constant pool
(with an exception for strings that, when MUTF-8 encoded, are longer than 64kB-1 because they won't fit into a single constant entry anymore so the Kotlin compiler inserts a runtime concatenation, but you won't be able to
const
it)
p
Does string end up in same constant pool in both cases (heap / stack)?
s
The constant pool is an independent construct from stack and heap
p
I see. Thanks for explaining guys!