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各种字符串拼接性能对比》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Ajax for Web Application Developers

Ajax for Web Application Developers

Kris Hadlock / Sams / 2006-10-30 / GBP 32.99

Book Description Reusable components and patterns for Ajax-driven applications Ajax is one of the latest and greatest ways to improve users’ online experience and create new and innovative web f......一起来看看 《Ajax for Web Application Developers》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具