How much is the overhead of using object vs val? I...
# getting-started
p
How much is the overhead of using object vs val? I understand that object instance created lazily on first call so there is one IF statement on each call and calls can be concurrent, so there must be some synchronization. Or maybe there are any optimizations for that in Kotlin compiler? Any suggestions for using object instead of val? + if there is possibility (any annotation) to tell compiler to make object with eager initialization?
e
on JVM, the pattern Kotlin emits leads to synchronization is in the classloader, effectively
Copy code
// object X
class MyObject {
    private MyObject();
    public static MyObject INSTANCE = new MyObject();
}
the classloader always synchronizes on the class being loaded anyways (required by java)
it's basically impossible to eagerly initialize on JVM (without some hacks like digging through the internals of the classpath), it doesn't load any classes until they are referenced
the implementation is different on non-JVM platforms of course, there is https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.js/-eager-initialization/ and https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.native/-eager-initialization/ on non-JVM platforms but those are workarounds for certain initialization ordering issues and may go away