What is the JavaScript convention for no operation?

前端 未结 6 1823
执念已碎
执念已碎 2020-11-30 18:00

What is the JavaScript convention for no operation? Like a Python pass command.

  • One option is simply an empty function: function() {}
6条回答
  •  盖世英雄少女心
    2020-11-30 18:46

    The most concise and performant noop is an empty arrow function: ()=>{}.

    Arrow functions work natively in all browsers except IE (there is a babel transform if you must):


    ()=>{} vs. Function.Prototype

    • ()=>{} is 87% faster than Function.prototype in Chrome 67.
    • ()=>{} is 25% faster than Function.prototype in Firefox 60.
    • ()=>{} is 85% faster than Function.prototype in Edge (6/15/2018).
    • ()=>{} is 65% less code than Function.prototype.

    The test below heats up using the arrow function to give bias to Function.prototype, yet the arrow function is the clear winner:

    const noop = ()=>{};
    const noopProto = Function.prototype;
    
    function test (_noop, iterations) {
        const before = performance.now();
        for(let i = 0; i < iterations; i++) _noop();
        const after = performance.now();
        const elapsed = after - before;
        console.info(`${elapsed.toFixed(4)}MS\t${_noop.toString().replace('\n', '')}\tISNOOP? ${_noop() === undefined}`);
        return elapsed;
    }
    
    const iterations = 10000000
    console.info(`noop time for ${iterations.toLocaleString()} iterations`)
    const timings = {
        noop: test(noop, iterations),
        noopProto: test(noopProto, iterations)
    }
    
    const percentFaster = ((timings.noopProto - timings.noop)/timings.noopProto).toLocaleString("en-us", { style: "percent" });
    console.info(`()=>{} is ${percentFaster} faster than Function.prototype in the current browser!`)

提交回复
热议问题