Java performance, story 1

Aleksandar Danilovic
Javarevisited
Published in
2 min readFeb 19, 2022

This is an introduction story from a future story serial about how to write performant Java code. In this story, a small but useful tip is given.

Photo by Jannik Selz on Unsplash

It is not easy to write highly performant code. When talking about performance, we usually mean high speed. If we also use small resources, then it is perfect.

Imagine that inside some method you call the same method for the same object more times, for example person.getAge() is called 3 times during method execution. And this method each time returns the same result as it is supposed to be as a person age changes once per year. :-)

This is an unnecessary waste of speed! The correct way is to use the local variable and call person.getAge() just once:

int personsAge = person.getAge();

Then you can change each person.getAge() usage with personsAge. If you continuously call person.getAge() knowing you always get the same value, then JVM must always stop the current method, prepare the stack for the next method (person.getAge()) and then call it, put the result integer value in the stack, and return, and put the integer back to the expression.

One last tip in this article: if you refactor similar code, please use your IDE tool for that! If you change each occurrence manually, then it’s possible to make some errors. Use your tools smartly as much as possible!

Conclusion

Writing highly performant code is not easy at all! This is just the beginning of the long journey. I will share my experiences and help you to also do the same. With examples — maybe they are just easy examples, but even then you can rarely find anywhere else such tips. Keep learning and see you!

--

--

Aleksandar Danilovic
Javarevisited

Work as Senior Java developer for 16 years. Publish stories about Java, algorithms, object oriented design, system design and programmers' life styles