简体   繁体   中英

Why is checking void 0 so much faster than checking undefined?

I noticed something interesting after using gulp-uglify on my concatenated javascript. I was passing in undefined to a global IIFE wrapper and I saw that it was changing it to void 0 . What the heck is void 0? I ran it in the console and it returned undefined. Interesting! This got me curious, so I started running tests on void 0. In my console tests (simple loops and timestamps), I have observed as much as a 180x speed increase, depending on browser, checking void 0 instead of undefined . Does anyone know why checking void 0 is so much faster?

(function(start, x, z){
    for (var i=0; i<z; i++){
      if (x === undefined){}
    }
    console.info('t1 ', Date.now() - start);
    start = Date.now();
    for (var i=0; i<z; i++){
      if (x === void 0){}
    }
    console.info('t1 ', Date.now() - start);
})(Date.now(), '', 1e6)

Actually, I just realized the difference between void 0 and undefined . undefined is a value on global scope and void is an operator. What's happening in this test is that undefined was being checked globally whereas void 0 , since it is an expression using the operator void , does not require scope traversal in order to check its value. If you pass in undefined to the IIFE wrapper, the test results will be the same. The performance discrepancy shown in the original test actually only measured the time-cost of scope traversal 1e6 times.

Further code proof that this is the case. The for loops below have the same execution time:

(function(start, x, z, undefined, c, Math){
    for (var i=0; i<z; i++){
    if (x !== undefined){
        c = Math.random();
    }
    }
    console.info('t1 ', Date.now() - start);
    start = Date.now();
    c = 0;
    for (var i=0; i<z; i++){
        if (x !== void 0){
            c = Math.random();
        }
    }
    console.info('t1 ', Date.now() - start);
})(Date.now(), '', 1e6, undefined, 0, Math)

rock star does make a good point that the results are subject to how your code is written, such as whether the conditionally assigned values in memory are accessed or not. Based on my tests, it will vary a lot if you take the values and pass it as an argument to a function. At that point the browser may decide to do fewer optimizations. Nevertheless, in every test I've run void 0 is still faster than or equivalent to undefined , uses less kb, and it removes concerns about traversing scope.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM