Is it faster (micro-optimization) to read a value ...
# getting-started
s
Is it faster (micro-optimization) to read a value from a function parameter or a local variable?
Copy code
fun foo(userId: Int) {
     doWork()
     val user = loadFromDb(userId)
     doMoreWork()
     //faster to refer to user.id or userId?
 }
c
I can’t imagine there would be any significant different between the two, especially in application-level code like the snippet you pasted. Don’t fall into the trap of optimizing your code too early, it’s rarely those kinds of things that cause noticeable performance degradation. IO (DB queries, reading files, network calls, etc) will almost always be the source of bottlenecks. Focus first on writing correct, readable code, then measure performance yourself to identify and fix your bottlenecks.
1
r
At this point, one could argue that the other segment of the code which needs the userId is a different piece of work and could be migrated into it's own separate function say
bar(userId:Int)
. From somewhere within your application, you could call them as
Copy code
foo(userId)
bar(userId)
and won't have to worry about which one is faster, but which one is more elegant and readable.
k
As others have said, there will usually be no significant performance difference, so focus on correct and readable code. But if there is nothing else to choose between the two - if both are just as readable and maintainable as each other - and the only consideration remaining is performance: note that
userId
is a primitive value taken from the stack, and that's very fast. The JIT will probably do further optimizations, such as possibly keeping it in a CPU register. On the other hand,
user.Id
involves possibly checking that
user
is not null, then calling
user.getId()
(a function call and a value access via indirection). However, even with this the JIT may optimize it.
s
This was somewhat of a theoretical question to understand the principles behind it.