Issue
According to https://www.geeksforgeeks.org/12-tips-to-optimize-java-code-performance/ at number 3, it says that during a for loop, you should define size beforehand and call that in the comparator. At first, that made sense to me assuming that the .size() method has to count up the elements every time it is called.
To verify this, I went to the source code for an ArrayList and went to the size method. What I found though was that it would just return an integer size that is stored as a value in the object. This is more of what I was expecting to find, but if this is the case, then why does the article say to avoid it? It does not explain why, it merely says to never do it. From what I saw, the list is already calling a variable that is stored in memory.
So, my question is: Is it actually going to help, or is it just something that the article got wrong?
Solution
The answer is: "it depends".
- It depends on what
List
class you are using. - It depends on how smart the JIT compiler is.
- It depends on whether the size of the list changes during the loop execution.
For the most common List
implementations, the current size is held in a field, and the size()
method simply returns that field. In such cases, the code of the size()
method will typically be inlined so that a size()
call is a efficient as accessing the field directly. If the JIT compiler is able to deduce that the field doesn't change (and if there are no relevant Java Memory Model related constraints) then it could conceivably cache the size()
result in a register.
But the flipside is that some List
implementations may compute the size, and the JIT compiler may not be able to do some or all of those optimizations.
But the flipside of the flipside is that if size()
is cheap, the overhead of calling it on each loop iteration may be too small to be significant.
Bottom line:
Beware of premature optimization.
Beware of articles that give overly simplistic / overly generalized advice.
Beware of articles that contain arrant nonsense like this:
If possible, we can use primitive types instead of objects since data access from stack memory is faster than heap memory1.
1 - This appears in "5. Use Primitive Types Wherever Possible". Stack and heap memory use the same hardware and have the same access times. The real point he should be making in that context is that getting the value of an Integer
involves an extra memory fetch, compared with accessing an int
.
Answered By - Stephen C
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.