Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clean code vs performance

Some principles of clean code are:

  • functions should do one thing at one abstraction level
  • functions should be at most 20 lines long
  • functions should never have more than 2 input parameters

How many cpu cycles are "lost" by adding an extra function call in Java?
Are there compiler options available that transform many small functions into one big function in order to optimize performance?

E.g.

void foo() {
  bar1()
  bar2()
}

void bar1() {
  a();
  b();
}
void bar2() {
  c();
  d();
}

Would become

void foo() {
  a();
  b();
  c();
  d();
}
like image 300
activity Avatar asked Mar 17 '18 10:03

activity


1 Answers

How many cpu cycles are "lost" by adding an extra function call in Java?

This depends on whether it is inlined or not. If it's inline it will be nothing (or a notional amount)

If it is not compiled at runtime, it hardly matters because the cost of interperting is more important than a micro optimisation, and it is likely to be not called enough to matter (which is why it wasn't optimised)

The only time it really matters is when the code is called often, however for some reason it is prevented from being optimised. I would only assume this is the case because you have a profiler telling you this is a performance issue, and in this case manual inlining might be the answer.

I designed, develop and optimise latency sensitive code in Java and I choose to manually inline methods much less than 1% of time, but only after a profiler e.g. Flight Recorder suggests there is a significant performance problem.

In the rare event it matters, how much difference does it make?

I would estimate between 0.03 and 0.1 micros-seconds in real applications for each extra call, in a micro-benchmark it would be far less.

Are there compiler options available that transform many small functions into one big function in order to optimize performance?

Yes, in fact what could happen is not only are all these method inlined, but the methods which call them are inlined as well and none of them matter at runtime, but only if the code is called enough to be optimised. i.e. not only is a,b, c and d inlined and their code but foo is inlined as well.

By default the Oracle JVM can line to a depth of 9 levels (until the code gets more than 325 bytes of byte code)

Will clean code help performance

The JVM runtime optimiser has common patterns it optimises for. Clean, simple code is generally easier to optimise and when you try something tricky or not obvious, you can end up being much slower. If it harder to understand for a human, there is a good chance it's hard for the optimiser to understand/optimise.

like image 58
Peter Lawrey Avatar answered Oct 08 '22 10:10

Peter Lawrey