kotlinoop

When to use long or int in Kotlin? Is there any difference in performance?


I was supporting a system made in Kotlin, and I noticed that some variables with integer values ​​are as int, while others are as long. Is there any difference in the use of the two types, considering the system performance?

For example:

val id: Long = 0, val age: Int = 0,

Why use different types in these cases?


Solution

  • Studying about "primitive types" in Kotlin (in quotation marks, as Kotlin does not have primitive types, the language uses classes for this), basically the difference between Int and Long is the amount of bits that each type can store.

    Int:

    Long:

    Therefore, if you store a value referring to age (something that varies between 0 and 120) in a variable of type Long, you will be mismanaging your system's memory resources, considering that a variable of type Int, which consumes Less memory would solve your problem.