Compiler bytecode optimization

Is planned any builtin bytecode optimization?

I understand that optimizations are done by JIT compilation and some optimizations cannot be even done earlier. Memory usage/slow startup time are major drawbacks of JVM and bloated bytecode won’t help (cost disk space, time of loading from disk to memory, consumption in memory, …).

When I check generated bytecode in Idea (/translation back to java), it is always full of

  • redundant variables,
  • statements like if (true) {…}
  • calls like Intrinsics.areEqual(“etf”, it) // isn’t better for just “etf”.equals(it) ?

Lot of redundant instructions are result of “inline” keyword which is key Kotlin feature.

Some kind of “cool” optimizations would be probably complex to implement and slowing down compilation, but wouldn’t worth to at least optimize cases like above?

1 Like

I’d be very surprised if the Kotlin compiler didn’t do some optimisations already.

Also, some optimisations might cause trouble for tools such as debuggers — for example, they couldn’t show the values of variables that had been removed. So the compiler might deliberately choose not to make those changes. Especially because:

As you say, the JVM will do lots of optimisations itself. (For example, it can use escape analysis to move short-lived objects from the heap to the stack, prune unused code, inline function calls, and suchlike — and much more advanced transformations too.) So while cases like you mention would cause bigger bytecode, they might not have any impact at runtime.

But while I can’t speak to the cases you list, in general: yes, it would certainly be good if the compiler performed any clear optimisations as long as they won’t affect valid code, debuggers etc. And if you spot any obvious candidates, feel free to point them out to JetBrains!

(Also, JVM optimisations won’t help Kotlin/JS or Kotlin/Native — though of course those compilers might well do specific optimisations for those platforms already.)