Should I avoid using Java Label Statements?

前端 未结 11 1454
北荒
北荒 2020-11-29 04:27

Today I had a coworker suggest I refactor my code to use a label statement to control flow through 2 nested for loops I had created. I\'ve never used them before because per

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 04:43

    I have use a Java labeled loop for an implementation of a Sieve method to find prime numbers (done for one of the project Euler math problems) which made it 10x faster compared to nested loops. Eg if(certain condition) go back to outer loop.

    private static void testByFactoring() {
        primes: for (int ctr = 0; ctr < m_toFactor.length; ctr++) {
            int toTest = m_toFactor[ctr];
            for (int ctr2 = 0; ctr2 < m_divisors.length; ctr2++) {
                // max (int) Math.sqrt(m_numberToTest) + 1 iterations
                if (toTest != m_divisors[ctr2]
                            && toTest % m_divisors[ctr2] == 0) {
                    continue primes; 
                }
            } // end of the divisor loop
        } // end of primes loop
    } // method
    

    I asked a C++ programmer how bad labeled loops are, he said he would use them sparingly, but they can occasionally come in handy. For example, if you have 3 nested loops and for certain conditions you want to go back to the outermost loop.

    So they have their uses, it depends on the problem you were trying to solve.

提交回复
热议问题