golang各种字符串拼接性能对比

栏目: Go · 发布时间: 5年前

内容简介:废话不多说,直接上代码看效果最终效果(多次尝试,对比结果都一致):

golang中字符串拼接方法

  1. +=
  2. fmt.sprintf
  3. append
  4. buffer.WriteString
  5. copy

废话不多说,直接上代码看效果

package main

import (
    "bytes"
    "fmt"
    "time"
)

func main() {
    str:="chinese"
    city:="beijing"
    
    // 1. +=
    s:=time.Now()
    for i:=0;i<100000;i++ {
        str +=city
    }
    e:=time.Since(s)
    fmt.Println("time cost 1:", e)
  
    // 2. fmt.Sprintf
    str="chinese"
    city="beijing"
    s=time.Now()
    for i:=0;i<100000;i++ {
        str = fmt.Sprintf("%s%s",str,city)
    }
    e=time.Since(s)
    fmt.Println("time cost 2:", e)
  
     //3.  buffer.WriteString
    str="chinese"
    city="beijing"
    s=time.Now()
    var buf= bytes.Buffer{}
    buf.WriteString(str)
    for i:=0;i<100000;i++ {
        buf.WriteString(city)
    }
    e=time.Since(s)
    fmt.Println("time cost 3:", e)

   //4. append
    str="chinese"
    city="beijing"
    s=time.Now()
    bstr:=[]byte(str)
    bcity:=[]byte(city)
    for i:=0;i<100000;i++ {
        bstr= append(bstr, bcity...)
    }
    e=time.Since(s)
    fmt.Println("time cost 4:", e)

  // 5. copy
    str="chinese"
    city="beijing"
    s=time.Now()
    zstr :=[]byte(str)
    for i:=0;i<100000;i++ {
        copy(zstr, city)
    }
    e=time.Since(s)
    fmt.Println("time cost 5:", e)
}

最终效果(多次尝试,对比结果都一致):

time cost 1: 3.176250251s
time cost 2: 5.347827717s
time cost 3: 1.051104ms
time cost 4: 769.258µs
time cost 5: 323.968µs

效率:copy > append > buf.WriteString > += > fmt.Sprintf

所以请慎用fmt.Sprinf 和 +=


以上所述就是小编给大家介绍的《golang各种字符串拼接性能对比》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Smarter Than You Think

Smarter Than You Think

Clive Thompson / Penguin Press HC, The / 2013-9-12 / USD 27.95

It's undeniable—technology is changing the way we think. But is it for the better? Amid a chorus of doomsayers, Clive Thompson delivers a resounding "yes." The Internet age has produced a radical new ......一起来看看 《Smarter Than You Think》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具