Node.js optimization with constants

Viewed 161

Please compare:

// Version 1
    const oneHour = 60 * 60
    function checkTime(timePast) {
        if (timePast<7 * 24 * oneHour) {
            // Do something
        }
    }

// Version 2
    const oneHour = 60 * 60
    const oneWeek = 7 * 24 * oneHour
    function checkTime(timePast) {
        if (timePast<oneWeek) {
            // Do something
        }
    }

During millions of calls to checkTime(), is version 2 faster than version 1, or is Node.js smart enough to make the extra calculation in version 1 only once?

2 Answers

You can easily check it like this:

    const oneHour = 60 * 60
    const oneWeek = 7 * 24 * oneHour;
    const randomData = generateArray();
    
    function generateArray () {
        let arr = [];

        for(i = 0; i < 10000000; i++) {
            arr.push(Math.floor(Math.random() * 10))
        }

        return arr;
    }

    function checkTime1(timePast) {
        if (timePast<7 * 24 * oneHour) {
            Math.random()
        }
    }

    function checkTime2(timePast) {
        if (timePast<oneWeek) {
            Math.random()
        }
    }

    console.time('checkTime1');
    randomData.forEach(i => checkTime1(i))
    console.timeEnd('checkTime1');

    console.time('checkTime2');
    randomData.forEach(i => checkTime2(i))
    console.timeEnd('checkTime2');

After several checks change order of "checkTime2" and "checkTime1", to be sure the result is valid. Seems Node.js is smart enough to make the extra calculation.

Related