Optimizing conditional code inside nested for-loops











up vote
2
down vote

favorite
1












Let's say I have some code that looks something like below.



boolean changecode = 0;

for (int i=0; i<4; i++) {
//some code
for (int j=0; j<4; j++) {
//some more code
if (changecode) {
//Code A
} else {
//Code B
}
}
}


This code would run the if-condition every time the loops were run, ending up executing it 16 times, which isn't really optimized. Now, I could of course do this:



boolean changecode = 0;

if (changecode) {
for (int i=0; i<4; i++) {
//some code
for (int j=0; j<4; j++) {
//some more code
//Code A
}
}
} else {
for (int i=0; i<4; i++) {
//some code
for (int j=0; j<4; j++) {
//some more code
//Code B
}
}
}


But i suppose this isn't really optimized either, thinking about all the repetition of code. Is there a way to make the conditional run in the outer layer and replace what code should be ran in the middle of the nested for-loop?










share|improve this question









New contributor




h7x4 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 3




    In your first code, the testing of a boolean being true would be very fast.
    – Scary Wombat
    1 hour ago






  • 3




    Expanding on what @ScaryWombat said, if the conditional does some complex computation, hoist the result of that out into a boolean on top, but leave the if (which is now very cheap -- and maybe JITable) inside the (non-duplicated) loop.
    – Thilo
    1 hour ago

















up vote
2
down vote

favorite
1












Let's say I have some code that looks something like below.



boolean changecode = 0;

for (int i=0; i<4; i++) {
//some code
for (int j=0; j<4; j++) {
//some more code
if (changecode) {
//Code A
} else {
//Code B
}
}
}


This code would run the if-condition every time the loops were run, ending up executing it 16 times, which isn't really optimized. Now, I could of course do this:



boolean changecode = 0;

if (changecode) {
for (int i=0; i<4; i++) {
//some code
for (int j=0; j<4; j++) {
//some more code
//Code A
}
}
} else {
for (int i=0; i<4; i++) {
//some code
for (int j=0; j<4; j++) {
//some more code
//Code B
}
}
}


But i suppose this isn't really optimized either, thinking about all the repetition of code. Is there a way to make the conditional run in the outer layer and replace what code should be ran in the middle of the nested for-loop?










share|improve this question









New contributor




h7x4 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 3




    In your first code, the testing of a boolean being true would be very fast.
    – Scary Wombat
    1 hour ago






  • 3




    Expanding on what @ScaryWombat said, if the conditional does some complex computation, hoist the result of that out into a boolean on top, but leave the if (which is now very cheap -- and maybe JITable) inside the (non-duplicated) loop.
    – Thilo
    1 hour ago















up vote
2
down vote

favorite
1









up vote
2
down vote

favorite
1






1





Let's say I have some code that looks something like below.



boolean changecode = 0;

for (int i=0; i<4; i++) {
//some code
for (int j=0; j<4; j++) {
//some more code
if (changecode) {
//Code A
} else {
//Code B
}
}
}


This code would run the if-condition every time the loops were run, ending up executing it 16 times, which isn't really optimized. Now, I could of course do this:



boolean changecode = 0;

if (changecode) {
for (int i=0; i<4; i++) {
//some code
for (int j=0; j<4; j++) {
//some more code
//Code A
}
}
} else {
for (int i=0; i<4; i++) {
//some code
for (int j=0; j<4; j++) {
//some more code
//Code B
}
}
}


But i suppose this isn't really optimized either, thinking about all the repetition of code. Is there a way to make the conditional run in the outer layer and replace what code should be ran in the middle of the nested for-loop?










share|improve this question









New contributor




h7x4 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











Let's say I have some code that looks something like below.



boolean changecode = 0;

for (int i=0; i<4; i++) {
//some code
for (int j=0; j<4; j++) {
//some more code
if (changecode) {
//Code A
} else {
//Code B
}
}
}


This code would run the if-condition every time the loops were run, ending up executing it 16 times, which isn't really optimized. Now, I could of course do this:



boolean changecode = 0;

if (changecode) {
for (int i=0; i<4; i++) {
//some code
for (int j=0; j<4; j++) {
//some more code
//Code A
}
}
} else {
for (int i=0; i<4; i++) {
//some code
for (int j=0; j<4; j++) {
//some more code
//Code B
}
}
}


But i suppose this isn't really optimized either, thinking about all the repetition of code. Is there a way to make the conditional run in the outer layer and replace what code should be ran in the middle of the nested for-loop?







java for-loop optimization nested-loops






share|improve this question









New contributor




h7x4 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




h7x4 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 1 hour ago





















New contributor




h7x4 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 1 hour ago









h7x4

134




134




New contributor




h7x4 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





h7x4 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






h7x4 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 3




    In your first code, the testing of a boolean being true would be very fast.
    – Scary Wombat
    1 hour ago






  • 3




    Expanding on what @ScaryWombat said, if the conditional does some complex computation, hoist the result of that out into a boolean on top, but leave the if (which is now very cheap -- and maybe JITable) inside the (non-duplicated) loop.
    – Thilo
    1 hour ago
















  • 3




    In your first code, the testing of a boolean being true would be very fast.
    – Scary Wombat
    1 hour ago






  • 3




    Expanding on what @ScaryWombat said, if the conditional does some complex computation, hoist the result of that out into a boolean on top, but leave the if (which is now very cheap -- and maybe JITable) inside the (non-duplicated) loop.
    – Thilo
    1 hour ago










3




3




In your first code, the testing of a boolean being true would be very fast.
– Scary Wombat
1 hour ago




In your first code, the testing of a boolean being true would be very fast.
– Scary Wombat
1 hour ago




3




3




Expanding on what @ScaryWombat said, if the conditional does some complex computation, hoist the result of that out into a boolean on top, but leave the if (which is now very cheap -- and maybe JITable) inside the (non-duplicated) loop.
– Thilo
1 hour ago






Expanding on what @ScaryWombat said, if the conditional does some complex computation, hoist the result of that out into a boolean on top, but leave the if (which is now very cheap -- and maybe JITable) inside the (non-duplicated) loop.
– Thilo
1 hour ago














3 Answers
3






active

oldest

votes

















up vote
2
down vote



accepted










In this particular case I would say it is pretty much the same. I would always go for the cleaner code over optimization (because it will be close to none if not none). The compiler will optimize/cache the result probably and even if it tests a boolean it is an operation that doesn't add performance loss. And longer code does ;) Also you can use an interface and some OOP pattern to avoid the repetition and the if/else. But it will add extra objects probably so just use the first option.






share|improve this answer




























    up vote
    2
    down vote













    I think the compiler will be able to optimize this away, but for the question's sake, you could do



    Runnable code = changecode 
    ? () -> codeA()
    : () -> codeB();
    for (int i=0; i<4; i++) {
    //some code
    for (int j=0; j<4; j++) {
    //some more code
    code.run();
    }
    }





    share|improve this answer

















    • 4




      Since the question seems to be about micro-optimizations, introducing an extra method call is maybe not the way forward (unless the compiler can remove it again)
      – Thilo
      1 hour ago










    • @Thilo afaik, method calls at this point are dirty cheap which means that it might still be faster than doing 16 conditional checks... hard to tell at such micro level
      – Sarief
      1 hour ago






    • 1




      @Sarief A method call is not going to be faster than checking an effectively-final boolean local variable (and also more difficult for an optimizer to reason about for further transformations)
      – Thilo
      1 hour ago








    • 1




      It's nice but for readability its better to make these methods. Otherwise the code will be very hard to read with anonymous pieces of code
      – Veselin Davidov
      50 mins ago










    • I upvoted the solution but just a little test (I am not sure if it is correct) showed that with two loops up to MaxInt and empty methods using functional interface takes 1900ms (consistent) and using if statement inside the for loop takes 1200ms. I am not saying it is 100% correct but still if we are talking for optimization this should be taken into account
      – Veselin Davidov
      38 mins ago




















    up vote
    1
    down vote













    As others pointed out, boolean comparison is very cheap performance-wise. It is not worth optimizing something like this just to make the code look worse.



    In my opinion it is very important not to overthink small things like this. Don't optimize it unless you see some performance problems and there is nothing else to improve.



    It is worth mentioning that very often the compiler will optimize it on its own, there is no need to bother. Btw. it might be worth checking this article about dumb code: https://www.oracle.com/technetwork/articles/java/devinsight-1-139780.html






    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });






      h7x4 is a new contributor. Be nice, and check out our Code of Conduct.










       

      draft saved


      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53370949%2foptimizing-conditional-code-inside-nested-for-loops%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      2
      down vote



      accepted










      In this particular case I would say it is pretty much the same. I would always go for the cleaner code over optimization (because it will be close to none if not none). The compiler will optimize/cache the result probably and even if it tests a boolean it is an operation that doesn't add performance loss. And longer code does ;) Also you can use an interface and some OOP pattern to avoid the repetition and the if/else. But it will add extra objects probably so just use the first option.






      share|improve this answer

























        up vote
        2
        down vote



        accepted










        In this particular case I would say it is pretty much the same. I would always go for the cleaner code over optimization (because it will be close to none if not none). The compiler will optimize/cache the result probably and even if it tests a boolean it is an operation that doesn't add performance loss. And longer code does ;) Also you can use an interface and some OOP pattern to avoid the repetition and the if/else. But it will add extra objects probably so just use the first option.






        share|improve this answer























          up vote
          2
          down vote



          accepted







          up vote
          2
          down vote



          accepted






          In this particular case I would say it is pretty much the same. I would always go for the cleaner code over optimization (because it will be close to none if not none). The compiler will optimize/cache the result probably and even if it tests a boolean it is an operation that doesn't add performance loss. And longer code does ;) Also you can use an interface and some OOP pattern to avoid the repetition and the if/else. But it will add extra objects probably so just use the first option.






          share|improve this answer












          In this particular case I would say it is pretty much the same. I would always go for the cleaner code over optimization (because it will be close to none if not none). The compiler will optimize/cache the result probably and even if it tests a boolean it is an operation that doesn't add performance loss. And longer code does ;) Also you can use an interface and some OOP pattern to avoid the repetition and the if/else. But it will add extra objects probably so just use the first option.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered 1 hour ago









          Veselin Davidov

          5,4761515




          5,4761515
























              up vote
              2
              down vote













              I think the compiler will be able to optimize this away, but for the question's sake, you could do



              Runnable code = changecode 
              ? () -> codeA()
              : () -> codeB();
              for (int i=0; i<4; i++) {
              //some code
              for (int j=0; j<4; j++) {
              //some more code
              code.run();
              }
              }





              share|improve this answer

















              • 4




                Since the question seems to be about micro-optimizations, introducing an extra method call is maybe not the way forward (unless the compiler can remove it again)
                – Thilo
                1 hour ago










              • @Thilo afaik, method calls at this point are dirty cheap which means that it might still be faster than doing 16 conditional checks... hard to tell at such micro level
                – Sarief
                1 hour ago






              • 1




                @Sarief A method call is not going to be faster than checking an effectively-final boolean local variable (and also more difficult for an optimizer to reason about for further transformations)
                – Thilo
                1 hour ago








              • 1




                It's nice but for readability its better to make these methods. Otherwise the code will be very hard to read with anonymous pieces of code
                – Veselin Davidov
                50 mins ago










              • I upvoted the solution but just a little test (I am not sure if it is correct) showed that with two loops up to MaxInt and empty methods using functional interface takes 1900ms (consistent) and using if statement inside the for loop takes 1200ms. I am not saying it is 100% correct but still if we are talking for optimization this should be taken into account
                – Veselin Davidov
                38 mins ago

















              up vote
              2
              down vote













              I think the compiler will be able to optimize this away, but for the question's sake, you could do



              Runnable code = changecode 
              ? () -> codeA()
              : () -> codeB();
              for (int i=0; i<4; i++) {
              //some code
              for (int j=0; j<4; j++) {
              //some more code
              code.run();
              }
              }





              share|improve this answer

















              • 4




                Since the question seems to be about micro-optimizations, introducing an extra method call is maybe not the way forward (unless the compiler can remove it again)
                – Thilo
                1 hour ago










              • @Thilo afaik, method calls at this point are dirty cheap which means that it might still be faster than doing 16 conditional checks... hard to tell at such micro level
                – Sarief
                1 hour ago






              • 1




                @Sarief A method call is not going to be faster than checking an effectively-final boolean local variable (and also more difficult for an optimizer to reason about for further transformations)
                – Thilo
                1 hour ago








              • 1




                It's nice but for readability its better to make these methods. Otherwise the code will be very hard to read with anonymous pieces of code
                – Veselin Davidov
                50 mins ago










              • I upvoted the solution but just a little test (I am not sure if it is correct) showed that with two loops up to MaxInt and empty methods using functional interface takes 1900ms (consistent) and using if statement inside the for loop takes 1200ms. I am not saying it is 100% correct but still if we are talking for optimization this should be taken into account
                – Veselin Davidov
                38 mins ago















              up vote
              2
              down vote










              up vote
              2
              down vote









              I think the compiler will be able to optimize this away, but for the question's sake, you could do



              Runnable code = changecode 
              ? () -> codeA()
              : () -> codeB();
              for (int i=0; i<4; i++) {
              //some code
              for (int j=0; j<4; j++) {
              //some more code
              code.run();
              }
              }





              share|improve this answer












              I think the compiler will be able to optimize this away, but for the question's sake, you could do



              Runnable code = changecode 
              ? () -> codeA()
              : () -> codeB();
              for (int i=0; i<4; i++) {
              //some code
              for (int j=0; j<4; j++) {
              //some more code
              code.run();
              }
              }






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered 1 hour ago









              daniu

              6,45021633




              6,45021633








              • 4




                Since the question seems to be about micro-optimizations, introducing an extra method call is maybe not the way forward (unless the compiler can remove it again)
                – Thilo
                1 hour ago










              • @Thilo afaik, method calls at this point are dirty cheap which means that it might still be faster than doing 16 conditional checks... hard to tell at such micro level
                – Sarief
                1 hour ago






              • 1




                @Sarief A method call is not going to be faster than checking an effectively-final boolean local variable (and also more difficult for an optimizer to reason about for further transformations)
                – Thilo
                1 hour ago








              • 1




                It's nice but for readability its better to make these methods. Otherwise the code will be very hard to read with anonymous pieces of code
                – Veselin Davidov
                50 mins ago










              • I upvoted the solution but just a little test (I am not sure if it is correct) showed that with two loops up to MaxInt and empty methods using functional interface takes 1900ms (consistent) and using if statement inside the for loop takes 1200ms. I am not saying it is 100% correct but still if we are talking for optimization this should be taken into account
                – Veselin Davidov
                38 mins ago
















              • 4




                Since the question seems to be about micro-optimizations, introducing an extra method call is maybe not the way forward (unless the compiler can remove it again)
                – Thilo
                1 hour ago










              • @Thilo afaik, method calls at this point are dirty cheap which means that it might still be faster than doing 16 conditional checks... hard to tell at such micro level
                – Sarief
                1 hour ago






              • 1




                @Sarief A method call is not going to be faster than checking an effectively-final boolean local variable (and also more difficult for an optimizer to reason about for further transformations)
                – Thilo
                1 hour ago








              • 1




                It's nice but for readability its better to make these methods. Otherwise the code will be very hard to read with anonymous pieces of code
                – Veselin Davidov
                50 mins ago










              • I upvoted the solution but just a little test (I am not sure if it is correct) showed that with two loops up to MaxInt and empty methods using functional interface takes 1900ms (consistent) and using if statement inside the for loop takes 1200ms. I am not saying it is 100% correct but still if we are talking for optimization this should be taken into account
                – Veselin Davidov
                38 mins ago










              4




              4




              Since the question seems to be about micro-optimizations, introducing an extra method call is maybe not the way forward (unless the compiler can remove it again)
              – Thilo
              1 hour ago




              Since the question seems to be about micro-optimizations, introducing an extra method call is maybe not the way forward (unless the compiler can remove it again)
              – Thilo
              1 hour ago












              @Thilo afaik, method calls at this point are dirty cheap which means that it might still be faster than doing 16 conditional checks... hard to tell at such micro level
              – Sarief
              1 hour ago




              @Thilo afaik, method calls at this point are dirty cheap which means that it might still be faster than doing 16 conditional checks... hard to tell at such micro level
              – Sarief
              1 hour ago




              1




              1




              @Sarief A method call is not going to be faster than checking an effectively-final boolean local variable (and also more difficult for an optimizer to reason about for further transformations)
              – Thilo
              1 hour ago






              @Sarief A method call is not going to be faster than checking an effectively-final boolean local variable (and also more difficult for an optimizer to reason about for further transformations)
              – Thilo
              1 hour ago






              1




              1




              It's nice but for readability its better to make these methods. Otherwise the code will be very hard to read with anonymous pieces of code
              – Veselin Davidov
              50 mins ago




              It's nice but for readability its better to make these methods. Otherwise the code will be very hard to read with anonymous pieces of code
              – Veselin Davidov
              50 mins ago












              I upvoted the solution but just a little test (I am not sure if it is correct) showed that with two loops up to MaxInt and empty methods using functional interface takes 1900ms (consistent) and using if statement inside the for loop takes 1200ms. I am not saying it is 100% correct but still if we are talking for optimization this should be taken into account
              – Veselin Davidov
              38 mins ago






              I upvoted the solution but just a little test (I am not sure if it is correct) showed that with two loops up to MaxInt and empty methods using functional interface takes 1900ms (consistent) and using if statement inside the for loop takes 1200ms. I am not saying it is 100% correct but still if we are talking for optimization this should be taken into account
              – Veselin Davidov
              38 mins ago












              up vote
              1
              down vote













              As others pointed out, boolean comparison is very cheap performance-wise. It is not worth optimizing something like this just to make the code look worse.



              In my opinion it is very important not to overthink small things like this. Don't optimize it unless you see some performance problems and there is nothing else to improve.



              It is worth mentioning that very often the compiler will optimize it on its own, there is no need to bother. Btw. it might be worth checking this article about dumb code: https://www.oracle.com/technetwork/articles/java/devinsight-1-139780.html






              share|improve this answer

























                up vote
                1
                down vote













                As others pointed out, boolean comparison is very cheap performance-wise. It is not worth optimizing something like this just to make the code look worse.



                In my opinion it is very important not to overthink small things like this. Don't optimize it unless you see some performance problems and there is nothing else to improve.



                It is worth mentioning that very often the compiler will optimize it on its own, there is no need to bother. Btw. it might be worth checking this article about dumb code: https://www.oracle.com/technetwork/articles/java/devinsight-1-139780.html






                share|improve this answer























                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  As others pointed out, boolean comparison is very cheap performance-wise. It is not worth optimizing something like this just to make the code look worse.



                  In my opinion it is very important not to overthink small things like this. Don't optimize it unless you see some performance problems and there is nothing else to improve.



                  It is worth mentioning that very often the compiler will optimize it on its own, there is no need to bother. Btw. it might be worth checking this article about dumb code: https://www.oracle.com/technetwork/articles/java/devinsight-1-139780.html






                  share|improve this answer












                  As others pointed out, boolean comparison is very cheap performance-wise. It is not worth optimizing something like this just to make the code look worse.



                  In my opinion it is very important not to overthink small things like this. Don't optimize it unless you see some performance problems and there is nothing else to improve.



                  It is worth mentioning that very often the compiler will optimize it on its own, there is no need to bother. Btw. it might be worth checking this article about dumb code: https://www.oracle.com/technetwork/articles/java/devinsight-1-139780.html







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered 13 mins ago









                  Amongalen

                  1429




                  1429






















                      h7x4 is a new contributor. Be nice, and check out our Code of Conduct.










                       

                      draft saved


                      draft discarded


















                      h7x4 is a new contributor. Be nice, and check out our Code of Conduct.













                      h7x4 is a new contributor. Be nice, and check out our Code of Conduct.












                      h7x4 is a new contributor. Be nice, and check out our Code of Conduct.















                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53370949%2foptimizing-conditional-code-inside-nested-for-loops%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Wiesbaden

                      Marschland

                      Dieringhausen