Home > other >  How does assigning more variables affect performance of an app?
How does assigning more variables affect performance of an app?

Time:09-12

I would say println(sum) is more readable than println(var1.roundToInt() var2.roundToInt()), which is very important in my opinion, but requires assigning a new variable. How does this affect app performance and memory usage? Is it technically more efficient to use println(var1.roundToInt() var2.roundToInt()), whether this is the same? Maybe some optimizations happen when compiling an app? I'm mainly asking about Android app, but also interested in how it works in other platforms, systems, or programming languages. Thanks.

import kotlin.math.roundToInt

fun main() {
    val var1 = 1.0   3.3
    val var2 = 5.8 - 1.99
    val sum = var1.roundToInt()   var2.roundToInt()
    println(var1.roundToInt()   var2.roundToInt())
    println(sum)
}

CodePudding user response:

In this case its unlikely you're actually storing more variables- between the initial compiler and the JIT compilation of the JVM it will probably be optimized away, so it will make no difference.

Ignoring that, lets say it actually did store it in multiple variables. Writing to a register takes fractions of a nanosecond. Writing to a log like you do in println will take microseconds. You're optimizing the part that ultimately doesn't matter. Don't worry about optimizations on that level unless you really know you need to (hint: you almost never need to, and if you do you should almost certainly be writing in C and not kotlin/Java).

  • Related