What is the best way to add two strings together?

前端 未结 12 524
自闭症患者
自闭症患者 2020-12-01 23:35

I read somewehere (I thought on codinghorror) that it is bad practice to add strings together as if they are numbers, since like numbers, strings cannot be changed. Thus, ad

12条回答
  •  感情败类
    2020-12-02 00:07

    Found this post from Google, and thought I'd run some benchmarks, as I was curious what the result would be. (Benchmarked over 10,000 iterations using a benchmarker that subtracts its own overhead.)

        Which                        2 strings   10 strings   50 strings
        ----------------------------------------------------------------
        $a[] then implode()         2728.20 ps      6.02 μs     22.73 μs
        $a . $a . $a                 496.44 ps      1.48 μs      7.00 μs
        $b .= $a                     421.40 ps ★    1.26 μs      5.56 μs
        ob_start() and echo $a      2278.16 ps      3.08 μs      8.07 μs
        "$a$a$a"                     482.87 ps      1.21 μs ★    4.94 μs ★
        sprintf()                   1543.26 ps      3.21 μs     12.08 μs
    

    So there's not much in it. Probably good to avoid sprintf() and implode() if you need something to be screaming fast, but there's not much difference between all the usual methods.

提交回复
热议问题