1

I'm new to Kotlin, but I want to try using it for game development, targeting at least Android with OpenGL ES 2.0 and HTML5 with WebGL (with which I am reasonably familiar). Not having to have slightly different versions of my rendering engine's classes/functions for WebGL and GLES20 would obviously be a good thing, but is there a practical way to achieve this in Kotlin without overhead?

I think what I'll have to do is write a class that implements WebGLRenderingContextBase or a clone of it (if a clone is necessary I can just use a delegate for the WebGL implementation) in OpenGL ES 2.0, full of methods like this:

override fun bindBuffer(target: Int, buffer, Int) {
    GLES20.glBindBuffer(target, buffer)
}

I'll write a script to do the bulk of the work.

My question is, is the compiler smart enough to optimise away such wrappers and use GLES20.glBindBuffer etc directly in my class' vtable, or whatever equivalent the JVM has? Presumably inline can't be of any use when calling an overridden method via a reference to an interface or base class.

realh
  • 962
  • 2
  • 7
  • 22

1 Answers1

2

The Kotlin compiler does not optimize the bytecode to this extent, and it does not need to: the JVM itself is quite good at optimizing the code.

Moreover, inline functions were not designed to be a performance tool in Kotlin, instead they are used for non-local control flow and code transformation that cannot be achieved without inlining.

Actually, the JVM performs a lot of optimizations, sparing the compilers from the necessity of optimizing the bytecode they generate on their side too much. And inlining is one of the optimizations the JVM can do. (1) (2) (3)

Though neither compilers nor JVM can inline native methods, because of completely different nature of the native code.

The Kotlin compiler, in turn, performs some local optimizations that do not affect the overall structure of the program. One more reason to do so is debugging experience which is hard to preserve with heavy optimizations. To check the exact Kotlin optimizations, you can try to disable them by adding the -Xno-optimize flag to the free compiler arguments, then look through the generated bytecode or do some benchmarking.

hotkey
  • 140,743
  • 39
  • 371
  • 326