javascriptperformancemathoperatorsbit

Do Left Shift and Right Shift have better performance compared to multiply and divide operations?


If I want to do the fastest way to calculate x * 2, which one should I use?

x << 1

or

x * 2

With the same logical thinking, if I want to do the fastest way to calculate x / 2, which one should I use?

x >> 1

or

x / 2

Why?


Solution

  • There's no difference:

    ` Chrome/127
    ---------------------------------------------------
    shift     ■ 1.00x | x1000000000 246 246 252 255 262
    multiply  ■ 1.00x | x1000000000 246 252 254 257 258
    --------------------------------------------------- `
    

    Open in the playground

    // @benchmark shift
    2 << 1
    
    // @benchmark multiply
    2 * 2
    
    /*@skip*/ fetch('https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js').then(r => r.text().then(eval));