Search code examples
javaperformancenested-loops

Java performance of redesigning nested loops into methods


Someone asked me about this and after reading some big O stuff I still can't figure out which of the 2 designs is faster.

If I have this kind of nested loop in one method

public void someMethod(){
    for (a=0;a<10;a++){
     for (b=0;b<10;b++){
      for (c=0;c<10;c++){
       for (d=0;d<10;d++){
       }
      }
     }
    }
}

and I decided to redesign the method and place the 2 inner for loops to another method something like this

public void someMethod(){
     for (a=0;a<10;a++){
         for (b=0;b<10;b++){
          2loopsMethod();
         }
        }
    }

public void 2loopsMethod(){
for (c=0;c<10;c++){
 for (d=0;d<10;d++){
 }
}

}

My question is will the redesigned method be alot faster that the original code since I placed it in another method or will it make no difference?


Solution

  • It should make no difference. You still have four levels of nested loops, so delegating part of the work to a method call will not be faster.

    (Technically the added overhead of the method call will make the second example slightly slower, but if your code is doing anything significant at all I'd be surprised if you can even measure the difference.)