In this Brainfuck v2.0 benchmark, the Java version seems to be equivalent to the Kotlin version, as far as I can tell.
However, it runs twice slower and uses much more memory. Why is that?
I would expect them to have very similar memory and speed characteristics, since both run on the JVM.
Disclaimer: the Kotlin benchmark code is the result of my contribution.
If you compare Java and Kotlin versions of the code you'll notice that they are actually different. Each one uses an idiomatic approach of the corresponding programming language to encode operations.
Java version uses enum OpT
combined with class Op
. To run the brainfuck code it uses an idiomatic Java switch (op.op)
on enum to select what to do.
Kotlin version uses sealed class Op
and an idiomatic Kotlin when (op)
on type of the operation that exploits Kotlin's flow-sensitive typing (aka smart-cast) to get nice and readable code.
It turns out that idiomatic Kotlin code executes faster on JVM (for no particularly good reason). You can rewrite Java code using the same approach as in Kotlin and you'll get the same performance, however such Java code would look ugly in Java and could not be considered an idiomatic implementation in Java.