Golang拼接字符串性能对比
g o l a n g golang golang的 s t r i n g string string类型是不可修改的,对于拼接字符串来说,本质上还是创建一个新的对象将数据放进去。主要有以下几种拼接方式
拼接方式介绍
1.使用 s t r i n g string string自带的运算符 + + +
ans = ans + s
2. 使用格式化输出 f m t . S p r i n t f fmt.Sprintf fmt.Sprintf
ans = fmt.Sprintf("%s%s", ans, s)
3. 使用 s t r i n g s strings strings的 j o i n join join函数
一般适用于将字符串数组转化为特定间隔符的字符串的情况
ans=strings.join(strs,",")
4. 使用 s t r i n g s . B u i l d e r strings.Builder strings.Builder
builder := strings.Builder{}
builder.WriteString(s)
return builder.String()
5. 使用 b y t e s . B u f f e r bytes.Buffer bytes.Buffer
buffer := new(bytes.Buffer)
buffer.WriteString(s)
return buffer.String()
6. 使用 [ ] b y t e []byte []byte,并且提前设置容量
ans := make([]byte, 0, len(s)*n)
ans = append(ans, s...)
性能对比
先写一个随机生成长度为 n n n的字符串的函数
func getRandomString(n int) string {var tmp = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"ans := make([]uint8, 0, n)for i := 0; i < n; i++ {ans = append(ans, tmp[rand.Intn(len(tmp))])}return string(ans)
}
接下来分别写出上述拼接方式的实现,假设每次都拼接n次字符串s后返回。
1.使用 s t r i n g string string自带的运算符 + + +
循环 n n n次,每次都令答案字符串 a n s + ans+ ans+源字符串 s s s
func plusOperatorJoin(n int, s string) string {var ans stringfor i := 0; i < n; i++ {ans = ans + s}return ans
}
2. 使用格式化输出 f m t . S p r i n t f fmt.Sprintf fmt.Sprintf
循环 n n n次,使用 f m t . S p r i n t f fmt.Sprintf fmt.Sprintf达到拼接的目的
func sprintfJoin(n int, s string) string {var ans stringfor i := 0; i < n; i++ {ans = fmt.Sprintf("%s%s", ans, s)}return ans
}
3. 使用 s t r i n g s strings strings的 j o i n join join函数
拼接同一个字符串的话不适合用 j o i n join join函数,所以跳过这种方式
4. 使用 s t r i n g s . B u i l d e r strings.Builder strings.Builder
初始化 s t r i n g s . B u i l d e r strings.Builder strings.Builder,循环 n n n次,每次调用 W r i t e S t r i n g WriteString WriteString方法
func stringBuilderJoin(n int, s string) string {builder := strings.Builder{}for i := 0; i < n; i++ {builder.WriteString(s)}return builder.String()
}
5. 使用 b y t e s . B u f f e r bytes.Buffer bytes.Buffer
初始化 b y t e s . B u f f e r bytes.Buffer bytes.Buffer,循环 n n n次,每次调用 W r i t e S t r i n g WriteString WriteString方法
func bytesBufferJoin(n int, s string) string {buffer := new(bytes.Buffer)for i := 0; i < n; i++ {buffer.WriteString(s)}return buffer.String()
}
6. 使用 [ ] b y t e []byte []byte,并且提前设置容量
定义 a n s ans ans为 b y t e byte byte数组,并提前设置容量为 l e n ( s ) ∗ n len(s)*n len(s)∗n
func bytesJoin(n int, s string) string {ans := make([]byte, 0, len(s)*n)for i := 0; i < n; i++ {ans = append(ans, s...)}return string(ans)
}
测试代码
先随机生成一个长度为10的字符串,然后拼接10000次。
package high_stringsimport "testing"func benchmark(b *testing.B, f func(int, string) string) {var str = getRandomString(10)for i := 0; i < b.N; i++ {f(10000, str)}
}func BenchmarkPlusOperatorJoin(b *testing.B) {benchmark(b, plusOperatorJoin)
}
func BenchmarkSprintfJoin(b *testing.B) {benchmark(b, sprintfJoin)
}
func BenchmarkStringBuilderJoin(b *testing.B) {benchmark(b, stringBuilderJoin)
}
func BenchmarkBytesBufferJoin(b *testing.B) {benchmark(b, bytesBufferJoin)
}
func BenchmarkBytesJoin(b *testing.B) {benchmark(b, bytesJoin)
}

测试结果:
使用 [ ] b y t e []byte []byte > s t r i n g s . B u i l d e r strings.Builder strings.Builder >= b y t e s . B u f f e r bytes.Buffer bytes.Buffer > f m t . S p r i n t f fmt.Sprintf fmt.Sprintf > + + +运算符
源码分析
1.使用 s t r i n g string string自带的运算符 + + +
代码在runtime\string.go里
// concatstrings implements a Go string concatenation x+y+z+...
// The operands are passed in the slice a.
// If buf != nil, the compiler has determined that the result does not
// escape the calling function, so the string data can be stored in buf
// if small enough.
func concatstrings(buf *tmpBuf, a []string) string {idx := 0l := 0count := 0for i, x := range a {n := len(x)if n == 0 {continue}if l+n < l {throw("string concatenation too long")}l += ncount++idx = i}if count == 0 {return ""}// If there is just one string and either it is not on the stack// or our result does not escape the calling frame (buf != nil),// then we can return that string directly.if count == 1 && (buf != nil || !stringDataOnStack(a[idx])) {return a[idx]}s, b := rawstringtmp(buf, l)for _, x := range a {copy(b, x)b = b[len(x):]}return s
}
- 首先计算拼接后的字符串长度
- 如果只有一个字符串并且不在栈上就直接返回
- 如果 b u f buf buf不为空并且 b u f buf buf可以放下这些字符串,就把拼接后的字符串放在 b u f buf buf里,否则在堆上重新申请一块内存
func rawstringtmp(buf *tmpBuf, l int) (s string, b []byte) {if buf != nil && l <= len(buf) {b = buf[:l]s = slicebytetostringtmp(&b[0], len(b))} else {s, b = rawstring(l)}return
}
// rawstring allocates storage for a new string. The returned
// string and byte slice both refer to the same storage.
// The storage is not zeroed. Callers should use
// b to set the string contents and then drop b.
func rawstring(size int) (s string, b []byte) {p := mallocgc(uintptr(size), nil, false)return unsafe.String((*byte)(p), size), unsafe.Slice((*byte)(p), size)
}
- 然后遍历数组,将字符串 c o p y copy copy过去
2. 使用 s t r i n g s . B u i l d e r strings.Builder strings.Builder
介绍: s t r i n g s . B u i l d e r strings.Builder strings.Builder用于使用 W r i t e Write Write方法高效地生成字符串,它最大限度地减少了内存复制
拼接过程: b u i l d e r builder builder里有一个 b y t e byte byte类型的切片,每次调用 W r i t e S t r i n g WriteString WriteString的时候,是直接往该切片里追加字符串。因为切片底层的扩容机制是以倍数申请的,所以对比1而言,2的内存消耗要更少。
**结果返回:**在返回字符串的 S t r i n g String String方法里,是将 b u f buf buf数组转化为字符串直接返回的。
扩容机制: 想要缓冲区容量增加 n n n个字节,扩容后容量变为 2 ∗ l e n + n 2*len+n 2∗len+n
// A Builder is used to efficiently build a string using Write methods.
// It minimizes memory copying. The zero value is ready to use.
// Do not copy a non-zero Builder.
type Builder struct {addr *Builder // of receiver, to detect copies by valuebuf []byte
}// String returns the accumulated string.
func (b *Builder) String() string {return unsafe.String(unsafe.SliceData(b.buf), len(b.buf))
}// grow copies the buffer to a new, larger buffer so that there are at least n
// bytes of capacity beyond len(b.buf).
func (b *Builder) grow(n int) {buf := make([]byte, len(b.buf), 2*cap(b.buf)+n)copy(buf, b.buf)b.buf = buf
}
// WriteString appends the contents of s to b's buffer.
// It returns the length of s and a nil error.
func (b *Builder) WriteString(s string) (int, error) {b.copyCheck()b.buf = append(b.buf, s...)return len(s), nil
}
3. 使用 b y t e s . B u f f e r bytes.Buffer bytes.Buffer
介绍: b y t e s . B u f f e r bytes.Buffer bytes.Buffer跟 s t r i n g s . B u i l d e r strings.Builder strings.Builder的底层都是 b y t e byte byte数组,区别在于扩容机制和返回字符串的 S t r i n g String String方法。
结果返回: 因为 b y t e s . B u f f e r bytes.Buffer bytes.Buffer实际上是一个流式的字节缓冲区,可以向尾部写入数据,也可以读取头部的数据。所以在返回字符串的 S t r i n g String String方法里,只返回了缓冲区里未读的部分,所以需要重新申请内存来存放返回的结果。内存会比 s t r i n g s . B u i l d e r strings.Builder strings.Builder稍慢一些。
扩容机制: 想要缓冲区容量至少增加 n n n个字节, m m m是未读的长度, c c c是当前的容量。
优化点在于如果 n < = c / 2 − m n <= c/2-m n<=c/2−m,也就是当前容量的一半都大于等于现有的内容(未读的字节数)加上所需要增加的字节数,就复用当前的数组,把未读的内容拷贝到头部去。
We can slide things down instead of allocating a new slice. We only need m+n <= c to slide, but we instead let capacity get twice as large so we don’t spend all our time copying.
我们可以向下滑动,而不是分配一个新的切片。我们只需要m+n<=c来滑动,但我们让容量增加了一倍,这样我们就不会把所有的时间都花在复制上。
否则的话也是 2 ∗ l e n + n 2*len+n 2∗len+n的扩张
// A Buffer is a variable-sized buffer of bytes with Read and Write methods.
// The zero value for Buffer is an empty buffer ready to use.
type Buffer struct {buf []byte // contents are the bytes buf[off : len(buf)]off int // read at &buf[off], write at &buf[len(buf)]lastRead readOp // last read operation, so that Unread* can work correctly.
}
// String returns the contents of the unread portion of the buffer
// as a string. If the Buffer is a nil pointer, it returns "<nil>".
//
// To build strings more efficiently, see the strings.Builder type.
func (b *Buffer) String() string {if b == nil {// Special case, useful in debugging.return "<nil>"}return string(b.buf[b.off:])
}
// WriteString appends the contents of s to the buffer, growing the buffer as
// needed. The return value n is the length of s; err is always nil. If the
// buffer becomes too large, WriteString will panic with ErrTooLarge.
func (b *Buffer) WriteString(s string) (n int, err error) {b.lastRead = opInvalidm, ok := b.tryGrowByReslice(len(s))if !ok {m = b.grow(len(s))}return copy(b.buf[m:], s), nil
}// grow grows the buffer to guarantee space for n more bytes.
// It returns the index where bytes should be written.
// If the buffer can't grow it will panic with ErrTooLarge.
func (b *Buffer) grow(n int) int {m := b.Len()// If buffer is empty, reset to recover space.if m == 0 && b.off != 0 {b.Reset()}// Try to grow by means of a reslice.if i, ok := b.tryGrowByReslice(n); ok {return i}if b.buf == nil && n <= smallBufferSize {b.buf = make([]byte, n, smallBufferSize)return 0}c := cap(b.buf)if n <= c/2-m {// We can slide things down instead of allocating a new// slice. We only need m+n <= c to slide, but// we instead let capacity get twice as large so we// don't spend all our time copying.copy(b.buf, b.buf[b.off:])} else if c > maxInt-c-n {panic(ErrTooLarge)} else {// Add b.off to account for b.buf[:b.off] being sliced off the front.b.buf = growSlice(b.buf[b.off:], b.off+n)}// Restore b.off and len(b.buf).b.off = 0b.buf = b.buf[:m+n]return m
}
字符串拼接性能及原理
GoLang bytes.Buffer基础使用方法详解
相关文章:
Golang拼接字符串性能对比
g o l a n g golang golang的 s t r i n g string string类型是不可修改的,对于拼接字符串来说,本质上还是创建一个新的对象将数据放进去。主要有以下几种拼接方式 拼接方式介绍 1.使用 s t r i n g string string自带的运算符 ans ans s2. 使用…...
【问题解决】web页面html锚点定位后内容被遮挡问题解决【暗锚】
正常的锚点跳转 a标签的href填写目标元素的id即可 <a href"#my_target">to div1</a> <div id"my_target">div1</div> 内容被顶栏遮挡示例 但是当id所在元素被嵌套多层flex和relative布局之后,跳转后部分内容会被遮挡…...
easyui datagrid无数据时显示无数据
这里写自定义目录标题 需求解决办法 需求 使用datagrid显示记录时,结果查询记录数为0,此时需要显示无数据。 示例代码 <table id"dg"></table>$(#dg).datagrid({url:datagrid_data.json,columns:[[{field:code,title:Code,widt…...
动态规划python简单例子-斐波那契数列
def fibonacci(n):dp [0, 1] [0] * (n - 1) # 初始化动态规划数组for i in range(2, n 1):dp[i] dp[i - 1] dp[i - 2] # 计算斐波那契数列的第 i 项print(dp)return dp[n] # 返回斐波那契数列的第 n 项# 示例用法 n 10 # 计算斐波那契数列的第 10 项 result fibonac…...
免 费 搭 建 多模式商城:b2b2c、o2o、直播带货一网打尽
鸿鹄云商 b2b2c产品概述 【b2b2c平台】,以传统电商行业为基石,鸿鹄云商支持“商家入驻平台自营”多运营模式,积极打造“全新市场,全新 模式”企业级b2b2c电商平台,致力干助力各行/互联网创业腾飞并获取更多的收益。从消…...
Python AttributeError: ‘NoneType‘ object has no attribute ‘shape‘如何解决
Python AttributeError: ‘NoneType‘ object has no attribute ‘shape‘ 运行出现上述错误,这个错误表示某个图像对象为 NoneType ,没有 shape 属性。通常情况下,这是因为 OpenCV 没有能够正确地加载图像,导致无法访问图像数据。…...
vue3自定义确认密码匹配验证规则
// 自定义确认密码匹配验证规则 const matchPassword (rules:any, value:any, callback:any) > {if (value ! addData.payPwd) {callback(new Error(两次密码输入不一致!))} else {callback()} }const rules reactive({payPwd: [{ required: true, message: &q…...
岗位所处定位,岗位职责
电子产品所需岗位:pcb设计电路板,fpga,嵌入式,应用层(前后端,移动端)。 PCB 岗位职责:1.负责器件.工程或者项目与技术验证类的PCB板设计工作;2.协助项目中部分模块的PCB(…...
2024阿里云服务器配置推荐方案
阿里云服务器配置怎么选择合适?CPU内存、公网带宽和ECS实例规格怎么选择合适?阿里云服务器网aliyunfuwuqi.com建议根据实际使用场景选择,例如企业网站后台、自建数据库、企业OA、ERP等办公系统、线下IDC直接映射、高性能计算和大游戏并发&…...
OceanBase原生分布式数据库
1.历史背景 在Java Web项目中,常常使用免费开源的MySQL数据库存储业务数据,按业界经验MySQL单库超过多大数据体量,或单表超过几百万条数据后就会出现查询变慢的情况,单实例数据库只能扩展物理资源(CPU、内存),来提升查…...
首次使用go-admin
go-admin 1.1 拉取 拉去后端代码 git clone https://github.com/go-admin-team/go-admin.git拉取前端代码 git clone gitgithub.com:go-admin-team/go-admin-ui.git 1.2 编译 cd ./go-admingo mod tidygo build1.3 配置文件的修改 这里可以可以根据自己的需要进行自定义两…...
软件工程概论---内聚性和耦合性
目录 一.耦合性 1.内容耦合 2.公共耦合 4.控制耦合 5.标记耦合(特征耦合) 6.数据耦合 7.非直接耦合 二.内聚性 1.偶然内聚 2.逻辑内聚 3.时间内聚 4.过程内聚 5.通信内聚 6.顺序内聚 7.功能内聚 一.耦合性 耦合性是指软件结构中模块相互…...
纯血鸿蒙「扩圈」100天,酝酿已久的突围
坦白讲,去年参加华为开发者大会看到HarmonyOS NEXT(仅运行鸿蒙原生应用,所以也称作「纯血鸿蒙」)的时候,小雷也没料想到鸿蒙原生应用生态的发展速度会如此之快。 9月25日,华为正式对外宣布启动HarmonyOS NE…...
UICollection Compositional Layout全详解
本文字数:8325字 预计阅读时间:45分钟 01 Collection View Layout全详解 UICollectionView在iOS中是构建复杂布局的强大工具。iOS13中引入的 UICollectionViewCompositionalLayout为创建自定义布局提供了全新的可能性。本文将深入探讨Compositional Lay…...
单例模式的模板
参考了网上的一些单例模式,自己也写一个模板。 要点: 线程安全性单例对象的唯一性 #include <mutex> //在模板类 Singleton 中,可以定义单例模式的实现细节 template <typename T> class Singleton { public://通过删除拷贝构造…...
C#基础-空处理
在c#中,值对象是没有办法赋值为null的。比如说,你想要定义一个布尔值,你的赋值数据要么得是true、要么就得是false,默认情况下我们永远没可能给这个布尔赋值为null,即使只是对这个变量进行声明而不初始化数据ÿ…...
测试平台开发vue组件化重构前端代码
基于 springbootvue 的测试平台开发 继续更新(人在魔都 T_T)。 这期其实并不是一个详细的开发过程记录,主要还是针对本次前端重构来聊聊几个关注点。 目前重构的总进度在80%,重构完的页面没什么变化,再回顾一下。 一…...
龍运当头--html做一个中国火龙祝大家龙年大吉
🐉效果展示 🐉HTML展示 <body> <!-- partial:index.partial.html --> <svg><defs><g id=...
Dockerfile语法和简单镜像构建
Dockerfile是一个用于定义Docker镜像的文本文件,包含了一系列的指令和参数,用于指示Docker在构建镜像时应该执行哪些操作,例如基于哪个基础镜像、复制哪些文件到镜像中、运行哪些命令等。 Dockerfile文件的内容主要有几个部分组成,…...
uniapp使用wxml-to-canvas开发小程序保存canvas图片
微信小程序官方解决方案:wxml-to-canvas 使用wxml-to-canvas要知道一些前提条件 1、只能画view,text,image 2、每个元素必须要设置宽高 3、默认是flex布局,可以通过flexDirection: "column"来改变排列方式 4、文字 必…...
Perplexity学术模式到底有多“实时”?我们用NIST标准测试集连续监控72小时,结果让3所常春藤图书馆紧急更新采购清单…
更多请点击: https://intelliparadigm.com 第一章:Perplexity学术模式到底有多“实时”?我们用NIST标准测试集连续监控72小时,结果让3所常春藤图书馆紧急更新采购清单… 实时性验证方法论 我们采用 NIST TREC 2023 Dynamic Filt…...
5个Zutilo技巧让你成为Zotero文献管理高手
5个Zutilo技巧让你成为Zotero文献管理高手 【免费下载链接】Zutilo Zotero plugin providing some additional editing features 项目地址: https://gitcode.com/gh_mirrors/zu/Zutilo 还在为Zotero的批量操作烦恼吗?每天面对成百上千的文献条目,…...
前端实战:用HTML/CSS/JS打造交互式生日蛋糕网页应用
1. 项目概述:一个用代码烘焙的生日惊喜最近给朋友准备生日礼物,不想再走寻常路,琢磨着送点特别的。作为一个整天和代码打交道的人,我决定用最熟悉的工具——HTML、CSS和JavaScript——亲手“烘焙”一个数字生日蛋糕。这个项目“Re…...
别再照搬Zynq教程了!手把手教你为Arty A7-35T配置MicroBlaze的SPI Flash启动(附时钟连接避坑指南)
别再照搬Zynq教程了!手把手教你为Arty A7-35T配置MicroBlaze的SPI Flash启动(附时钟连接避坑指南) 在FPGA开发领域,Zynq系列因其ARMFPGA的异构架构而广受欢迎,网上教程资源也最为丰富。但这也导致了一个常见陷阱——许…...
Google Meet开启Gemini字幕后CPU飙升300%?资深SRE教你用Chrome Tracing+Gemini Profiling Dashboard精准定位瓶颈
更多请点击: https://intelliparadigm.com 第一章:Google Meet开启Gemini字幕后CPU飙升300%?资深SRE教你用Chrome TracingGemini Profiling Dashboard精准定位瓶颈 当团队在Google Meet中启用Gemini实时字幕功能后,参会终端Chrom…...
Dell G15终极散热控制指南:开源热控中心完全教程
Dell G15终极散热控制指南:开源热控中心完全教程 【免费下载链接】tcc-g15 Thermal Control Center for Dell G15 - open source alternative to AWCC 项目地址: https://gitcode.com/gh_mirrors/tc/tcc-g15 厌倦了官方AWCC软件的臃肿和卡顿?想要…...
利用MCP协议与Crypto APIs为AI助手集成多链交易数据查询能力
1. 项目概述:一个为AI助手注入区块链洞察力的MCP服务器 如果你和我一样,日常开发中经常需要查询不同区块链上的交易详情——比如验证一笔以太坊上的USDT转账是否成功,或者追溯某个比特币地址的资金来源——那你肯定体会过在十几个浏览器标签…...
XXMI启动器终极指南:一站式游戏模组管理平台完整教程
XXMI启动器终极指南:一站式游戏模组管理平台完整教程 【免费下载链接】XXMI-Launcher Modding platform for GI, HSR, WW and ZZZ 项目地址: https://gitcode.com/gh_mirrors/xx/XXMI-Launcher 还在为多个游戏模组管理而烦恼吗?XXMI启动器作为一款…...
MTKClient终极指南:解锁联发科设备的完整刷机与调试解决方案
MTKClient终极指南:解锁联发科设备的完整刷机与调试解决方案 【免费下载链接】mtkclient MTK reverse engineering and flash tool 项目地址: https://gitcode.com/gh_mirrors/mt/mtkclient 你是否曾经遇到过联发科设备变砖无法启动的困境?或者想…...
无线充电技术解析:从Qi标准到射频远距充电的现状与未来
1. 无线充电的现状与用户困境作为一名长期关注消费电子与网络通信设备的技术博主,我每天打交道最多的就是各种“电老虎”和“充电宝”。Rebecca Day在文章里描述的那个圣诞场景,我简直不能再熟悉了——在一堆新设备的包装盒里翻找线缆,在抽屉…...
