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




















  • 3




    In your first code, the testing of a boolean being true would be very fast.
    – Scary Wombat
    Nov 19 at 8:39






  • 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
    Nov 19 at 8:41

















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




















  • 3




    In your first code, the testing of a boolean being true would be very fast.
    – Scary Wombat
    Nov 19 at 8:39






  • 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
    Nov 19 at 8:41















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















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















share|improve this question













share|improve this question




share|improve this question








edited Nov 19 at 8:39

























asked Nov 19 at 8:38









h7x4

135




135








  • 3




    In your first code, the testing of a boolean being true would be very fast.
    – Scary Wombat
    Nov 19 at 8:39






  • 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
    Nov 19 at 8:41
















  • 3




    In your first code, the testing of a boolean being true would be very fast.
    – Scary Wombat
    Nov 19 at 8:39






  • 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
    Nov 19 at 8:41










3




3




In your first code, the testing of a boolean being true would be very fast.
– Scary Wombat
Nov 19 at 8:39




In your first code, the testing of a boolean being true would be very fast.
– Scary Wombat
Nov 19 at 8:39




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
Nov 19 at 8:41






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
Nov 19 at 8:41














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
      Nov 19 at 8:44










    • @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
      Nov 19 at 8:52






    • 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
      Nov 19 at 8:56








    • 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
      Nov 19 at 9:07










    • 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
      Nov 19 at 9:19




















    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
      });


      }
      });














      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 Nov 19 at 8:43









          Veselin Davidov

          5,5561515




          5,5561515
























              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
                Nov 19 at 8:44










              • @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
                Nov 19 at 8:52






              • 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
                Nov 19 at 8:56








              • 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
                Nov 19 at 9:07










              • 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
                Nov 19 at 9:19

















              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
                Nov 19 at 8:44










              • @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
                Nov 19 at 8:52






              • 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
                Nov 19 at 8:56








              • 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
                Nov 19 at 9:07










              • 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
                Nov 19 at 9:19















              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 Nov 19 at 8:41









              daniu

              6,69821634




              6,69821634








              • 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
                Nov 19 at 8:44










              • @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
                Nov 19 at 8:52






              • 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
                Nov 19 at 8:56








              • 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
                Nov 19 at 9:07










              • 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
                Nov 19 at 9:19
















              • 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
                Nov 19 at 8:44










              • @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
                Nov 19 at 8:52






              • 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
                Nov 19 at 8:56








              • 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
                Nov 19 at 9:07










              • 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
                Nov 19 at 9:19










              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
              Nov 19 at 8:44




              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
              Nov 19 at 8:44












              @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
              Nov 19 at 8:52




              @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
              Nov 19 at 8:52




              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
              Nov 19 at 8:56






              @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
              Nov 19 at 8:56






              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
              Nov 19 at 9:07




              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
              Nov 19 at 9:07












              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
              Nov 19 at 9:19






              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
              Nov 19 at 9:19












              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 Nov 19 at 9:44









                  Amongalen

                  1429




                  1429






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      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

                      If I really need a card on my start hand, how many mulligans make sense? [duplicate]

                      Alcedinidae

                      Can an atomic nucleus contain both particles and antiparticles? [duplicate]