Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell the efficiency of a Java code

I just realized that I have no idea on how to tell whether or not a piece of Java code is efficient from the computational point of view. Reading several source codes sometimes I feel that the code I'm reading is highly inefficient, some other times I feel the opposite.

Could you list the basic one-line rules to respect and why they are so important?

edit - My question is related to the Java implementations of the JVM, so things like Java allocation issues, String management, exception handling, thread synchronization and so on.

Thanks in advance

p.s. don't take the "one-line" literally pls

like image 595
Jack Avatar asked Nov 28 '22 10:11

Jack


2 Answers

Basic one-line rule? Okay, here you go:

Avoid unnecessary computations.

How do you do it? Sorry, no one-line answer to that. :(

Well, people spends years in college learning about algorithms and data structures in computer science for a reason... might want to take a course on algorithms/data structures sometime.


I'm not sure what you mean by "from a computation point of view" (it seems to imply algorithm issues), but assuming you mean tricks more similar to things like profiling, try these:

  • Run the program, then suddenly pause it, and see where it paused. Do this a few times; wherever it stops the most is a bottleneck, and how often it stops indicates how bad of a bottleneck it is.

  • Avoid boxing/unboxing (converting between int and Integer, etc.); especially avoid Integer[], List<Integer>, and other things that internally store arrays of objects of primitive types

  • Factor out common code (sometimes a speed issue, sometimes readability)

  • Avoid looping with String operations; use StringBuilder/StringBuffer instead. (In short, avoid creating and/or copying data when that's not needed.)

I'll add to this if other things come to mind.

like image 65
user541686 Avatar answered Dec 01 '22 01:12

user541686


Use profiling. Look at JProfile or for any other profilers.

like image 39
Roman Avatar answered Dec 01 '22 01:12

Roman