-1

For example, When looking at the code under a microscope, does this first code block use more computational time than the second code block?

code block 1:

method1() {
do something;
call method2;
}
method2() {
do something simple like assign a variable value;
}

code block 2:

method1(){
do something;
do something simple like assign a variable value;
}

Pretty simple, but I'm looking to see if anyone here knows what the value is in considering this (e.g. optimizing a program for minimal computational time).

As an example, I learned that gates in a circuit have a finite "Delta delay" in which it is possible to add up to see the maximum delay that the circuit will have when considering the clock speed in the design. Does Java have something similar to the Delta delay?

Numbers682
  • 129
  • 1
  • 11
  • 12
    Don't waste your time worrying about this, until you can prove by benchmarking that this is the most significant performance problem you have. The JIT will inline methods if it determines that to be better; you should focus on writing readable, maintainable code. – Andy Turner Apr 21 '17 at 15:17
  • 3
    You may actually gain performance by using short methods. Once I split a very long method manually and gained 40% speed. The JIT can inline, but not "outline" methods, so readability and performance are often positively correlated. – maaartinus Apr 21 '17 at 16:14

2 Answers2

6

Maybe, maybe not. Through a process called inlining, the JVM can execute the first code as if it was the second. See What is method inlining?

Anyway, when writing non-trivial applications, you should focus on readability and maintainability rather than minimal performance gains. In most cases, the difference in terms of resource usage will hardly, if at all, be noticeable. For the human reader, on the other hand, a long method that does too many different things can be a real pain.

Community
  • 1
  • 1
Erich Kitzmueller
  • 36,381
  • 5
  • 80
  • 102
4

It really depends on what is in method2() and how many parameters are going on the stack. The rule of thumb is, combining methods together by reducing code maintainability is never a good idea, the rare savings in speed are close to statistical fluke while the chance to introduce bugs or slowdowns in logic is much much higher.

If you really care about performance that much, I suggest you learn about JMH and micro-benchmarking using e.g. this tutorial. It will be very revealing and with the time you will learn about certain patterns.

E.g. coding in a certain style can allow your data fully reside in CPU caches providing orders of magnitude in speed up vs. an extra method call that in the absolute worst case might take a fraction of a percentage point.

Alex Pakka
  • 9,466
  • 3
  • 45
  • 69