Are ES6 template literals faster than string concatenation?

前端 未结 5 1239
予麋鹿
予麋鹿 2020-11-27 13:37

Does HTML code generation run measurably faster in modern browsers when using string concatenation or template literals in ES6?

For example:

String con

5条回答
  •  感情败类
    2020-11-27 14:19

    I did a naive test on node.js v6.0.0 and got nearly the same performance. Since the test is so naive, don't believe the numbers too much. But it seems the JIT compiler generates very optimised code nowadays. This let me decide to prefer templates over concatenation for my node apps.

    For reference this is the code I used:

    'use strict'
    
    function strConcat(i) {
        return 'abc' + i + 'def'
    }
    
    function strTemplate(i) {
        return `abc${i}def`
    }
    
    function run(strategy) {
        let before = new Date().getTime()
        let len = 0
        for ( let i = 0; i < 10000000; i+=1 ) {
            len += strategy(i).length
        }
        console.log(len + ' - ' + ((new Date().getTime()) - before) + 'ms')
    }
    
    console.log('strConcat')
    run(strConcat)
    
    console.log('strTemplate')
    run(strTemplate)
    

    And the output was:

    strConcat
    128888890 - 1904ms
    strTemplate
    128888890 - 1979ms
    

    I used len to absolutely make sure that the optimizer doesn't optimize the whole loop away. Anyway, it is still a very simple test. Maybe someone can make a more sophisticated one.

提交回复
热议问题