Does the `!!` operator have any overhead, if the v...
# announcements
k
Does the
!!
operator have any overhead, if the value is never
null
? I'm guessing no, but still...
z
you can always look at the bytecode it generates
n
Normally, yes, that sort of thing would have overhead in general. That said, I think at least some JVM implementations use a clever approach where they basically just go ahead and dereference it and let the OS hand them a segfault, which they handle with a signal handler
k
@Nir yeah, that's how Java / HotSpot works (depending on the profile of the code), either checks for null or in most cases just goes ahead and dereferences the variable
Does Kotlin add any other code to
!!
besides what the Java code would have?
a
The answer is yes. The compiler will insert
Intrinsics.checkNotNull()
calls. It should be trivial when the parameter is not null but if you really care you can use code shrinkers such as ProGuard or R8 to strip out the calls.
e
or
Intrinsics.throwNpe()
k
cool, thanks for the info
e
there is an optimization to remove duplicate null checks but otherwise yes, the Kotlin compiler emits explicit checks
a
It’s
Intrinsics.throwJavaNpe()
since Kotlin 1.4 and it’s called inside
Intrinsics.checkNotNull()
.
k
I'll research it a bit more in detail, as soon as I find out how to decompile Kotlin to JVM bytecodes, and further to generated assembly...
e
the JVM itself may handle NPEs by mapping the null page and trapping SIGSEGV (at least OpenJDK does), you won't be able to see that even in the generated assembly as that's set up by the runtime
but java bytecode is easy, just run
javap -v
on the emitted classfile, or use the built-in IDE decompiler
n
trying to map kotlin all the way to native assembly, via the JVM, seems like it would be extremely hard, what with all the JIT'ing optimizations
e
it's actually quite doable through the javaagent/JVMTI
that's what jconsole (which ships with the JDK) uses
n
but there's no guarantee that the same kotlincode even corresponds to the same assembly over time
as the JIT optimizes things, it can change
e
correct, and it changes across different Hotspot versions, and there's multiple JITs other than Hotspot (OpenJ9, Falcon...), and then of course running on Substrate/GraalVM and Dalvik/ART also "run" Java bytecode, but with an AoT compile/transform step first...