Break out of nested loops: return or label / break?

I am using a JavaScript function to set a global variable. Below, I have two really dumb example functions. One uses a shortcut to exit nested loops. Another uses an empty return.

My question is: which is better from a performance issue? (For the sake of argument, let's say you did this several million times.)

Using an empty return

function foo() {
    for(var i = 0; i < 100; ++i) {
        for(var j = 0; j < 100; ++j) {
            if(i * j == 50) {
                myGlobal = j;
                return;
            }
        }
    }
}

Using tag and break

function foo() {
    dance:
    for(var i = 0; i < 100; ++i) {
        for(var j = 0; j < 100; ++j) {
            if(i * j == 50) {
                myGlobal = j;
                break dance;
            }
        }
    }
}

I know that I will do nothing but complete the function after my internal condition is fulfilled / do my job.

Thank!

+4
source share
4 answers

( Chrome, MBP 2013, OSX 10.9, Intel i7 @2.8GHz, 16GB DDR3), . . return label/break . /, . :

function r() {
    for(var i = 0; i < 10; ++i) {
        for(var j = 0; j < 10; ++j) {
            if(i*j == 50) {
                return;
            }
        }
    }
}

function b() {
    dance:
    for(var i = 0; i < 10; ++i) {
        for(var j = 0; j < 10; ++j) {
            if(i*j == 50) {
                break dance;
            }
        }
    }
}

function r2() {
    return;
}

function b2() {
    dance:
    break dance;
}

var startTime;
var endTime;

console.log("Return test");
startTime = Date.now();
for(var i = 0; i < 1000000000; ++i) {
    r2();
}
endTime = Date.now();
console.log(endTime - startTime);

console.log("Break test");
startTime = Date.now();
for(var i = 0; i < 1000000000; ++i) {
    b2();
}
endTime = Date.now();
console.log(endTime - startTime);

( r() b()), . return label/break ( r2() b2()) / . :

1, 10000000

() : 1215

() 3- /, : 1522

2, 1000000000 // 2

() 3 : 1879

() 3 /: 1862

:

return ~ 25%

/HPC / 1%

+4

return, , . , , , , -. , , , return , , .

0

UPDATE:

: JavaScript ?, : " , --". , break, , return

0

Both have the same performance; the first is perhaps more readable. However, the latter makes it easier to change the function if you need to add additional instructions in the future after loops.

0
source

Source: https://habr.com/ru/post/1532057/


All Articles