1

Consider the following code:

public void doSomething(Foo foo) {
    for (int i = 0; i < factorial(foo.getSize()); i++) {
      //...
    }
}

public void doSomethingAnotherWay(Foo foo) {
    int max = factorial(foo.getSize());
    for (int i = 0; i < max; i++) {
        //...
    }
}

public static int factorial(int n) {
    //...
}

At a first glance, in the function doSomething the factorial function (or whatever other function takes its place) is evaluated several times whereas it is only evaluated once in the function doSomethingAnotherWay. Suppose the factorial function is expensive to compute.

Would it be worthwhile to store its result in a variable before the loop or is this something that the compiler would optimize anyways?

Does the factorial function have to be static for this optimization to occur (because then its output is always determined by its input)? What if foo.getSize() can change (via a setter, for example)? How would optimizations like this work in general?

Amaar
  • 337
  • 2
  • 13
  • 2
    @ScaryWombat Well, doing a **really** meaningful performance measurement would require a bit more than "debug it and see" ;-) – GhostCat Aug 27 '19 at 05:49
  • I doubt the Java compiler would be smart enough to figure out to refactor your code using dynamic programming (which is what you should be using here). You should go with the second DP approach, written and tested by your own hand. – Tim Biegeleisen Aug 27 '19 at 05:49
  • Considering factorial only gives the correct result for an int up to 13 (or something like), the difference would be negligible where it's actually correct. – Andy Turner Aug 27 '19 at 05:49
  • @AndyTurner I just used factorial to illustrate the idea. The actual function I'm using is different. With factorial a lookup table would probably be better anyways. – Amaar Aug 27 '19 at 05:51

0 Answers0