https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

rednifre

07/10/2023, 10:20 AM
Do these two snippets compile to the same byte code, or is one of them better at runtime?: Nice code:
Copy code
for (e in stuff) {
  val foo = bar(e)
  ...
}
Less allocations? Or unnecessary optimization?:
Copy code
var foo: Foo
for (e in stuff) {
  foo = bar(e)
  ...
}
e

ephemient

07/10/2023, 10:26 AM
I wouldn't even call it an unnecessary optimization. it is not an optimization to begin with
r

rednifre

07/10/2023, 10:26 AM
Interesting, wouldn’t you create a new val on every iteration in the first example?
s

Sam

07/10/2023, 10:26 AM
You can examine the byte code yourself in IntelliJ using Tools > Kotlin > Show Kotlin bytecode (and then decompile it back to Java, if that floats your boat). The actual bytecode can and will vary depending on what context this snippet appears in. And the JIT compiler will change it even further when you actually run it. In practice, you will not see any actual impact at runtime from changing your code in ways like this.
gratitude thank you 1
e

ephemient

07/10/2023, 10:27 AM
even a non-optimizing compiler will reuse the same register for the loop variable
r

rednifre

07/10/2023, 10:29 AM
Isn’t
e
the loop variable? I was asking about variables scoped to the block of each iteration?
e

ephemient

07/10/2023, 10:33 AM
I have a hard time imagining what you think might even be expensive with that
if the loop isn't unrolled, it's literally using the same instructions and layout on each iteration
Kotlin is not C++ with placeable complex objects and RVO. it is (mostly) Java's object model so a local variable is either a field or a reference.
v

Vampire

07/10/2023, 3:04 PM
Also, don't try to micro-optimize upfront. 1. Make your code working like intended, optimally with tests verifying the behavior 2. Make your code nice by refactoring. Here the tests from 1. come in handy to not accidentally change the behavior 3. Make your code fast / efficient, but only where you actually have a measurable performance or memory problem. 80% of the time is spent in 20% of the code and there is not much point in optimizing the other 80% except for readability and maintainability. For example a method that runs once a day, is not worth the effort and reduced maintainability. But a method that runs once a second night pretty well be.
💯 2