一文学会Golang里拼接字符串的6种方式(性能对比)
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里拼接字符串的6种方式(性能对比)
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. 使用…...

【笔记】Linux下编译Python3.10.15为动态库同时正确处理OpenSSL3依赖
之前自己第一次编译Python后发现pip会提示无法使用SSL,后来了解到是自己编译时没有配置OpenSSL。这个过程有点曲折,里面有一个坑,怕忘记于是写博客记录一下。 首先是下载OpenSSL,Python3.10.15支持此时最新版的OpenSSL 3.4.0&…...

Go语言获取客户端真实IP
在一些需求中,服务器需要记录客户端的ip地址,要获取ip地址,则需要有http.Request的对象参数传入,以下代码直接放在util中使用。 文件名:ip_utils.go package utilsimport ("context""github.com/spf1…...

大模型论文速递(11.23-11.25)
BlueLM-V3B 关键词:动态分辨率,图像放大,适应性网格化方法 研究问题:如何改进现有的动态分辨率匹配方法以减少在模型训练和部署中的计算复杂度? 方法: 分析现有动态分辨率匹配算法(如LLaVA-…...

维护在线重做日志(二)
迁移和重命名 可以使用操作系统命令重新定位重做日志,然后使用ALTER DATABASE语句使数据库知道它们的新名称(位置)。这个过程是必要的,例如,如果当前用于一些重做日志文件的磁盘将被删除,或者如果数据文件…...

.net core MVC入门(一)
文章目录 项目地址一、环境配置1.1 安装EF core需要包1.2 配置数据库连接二、使用EF创建表2.1 整体流程梳理2.1 建表详细流程三、添加第一个视图3.1整体流程梳理3.1 添加视图,并显示在web里四、使用EF增加Catogory数据,并且读取数据到页面4.1整体流程梳理4.2 实现五、增加Cat…...

802.11协议
802.11协议是由美国电气和电子工程师协会(IEEE)制定的无线局域网(WLAN)标准。以下是关于802.11协议的详细介绍: 一、定义与背景 定义:IEEE802.11是美国电机电子工程师协会(IEEE)为…...

【Linux】线程ID与互斥、同步(锁、条件变量)
作者主页: 作者主页 本篇博客专栏:Linux 创作时间 :2024年11月24日 线程ID及进程地址空间布局 先看一下这段代码: 运行一下: 运行这个代码之后,我们看到的这个很大的数字就是线程id,然后…...

Android 13 编译Android Studio版本的Launcher3
Android 13 Aosp源码 源码版本 Android Studio版本 Launcher3QuickStepLib (主要代码) Launcher3ResLib(主要资源) Launcher3IconLoaderLib(图片加载,冲突资源单独新建) 需要值得注意的是: SystemUISharedLib.jar 有kotlin和java下的,在 Lau…...

burp功能介绍
声明! 学习视频来自B站up主 **泷羽sec** 有兴趣的师傅可以关注一下,如涉及侵权马上删除文章,笔记只是方便各位师傅的学习和探讨,文章所提到的网站以及内容,只做学习交流,其他均与本人以及泷羽sec团队无关&a…...

Android12 的 Vold梳理
1.代码位置 system/vold/ 路径下,查看bp文件,发现是编译system/vold/main.cpp编译生成可执行文件vold 2.app侧调用代码流程 2.1 整体框架 #mermaid-svg-lqO8phN62rKNW407 {font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#…...

[pdf,epub]162页《分析模式》漫谈合集01-35提供下载
《分析模式》漫谈合集01-35的pdf、epub文件,已上传至本号的CSDN资源。 如果CSDN资源下载有问题,可到umlchina.com/url/ap.html。 已排版成适合手机阅读,pdf的排版更好一些。 ★UMLChina为什么叒要翻译《分析模式》? ★[缝合故事…...

Vue2教程003:Vue指令之v-bind和v-for
文章目录 2.6 v-bind2.7 图片轮播案例2.8 v-for2.9 图书管理案例 2.6 v-bind 作用:动态设置html的标签属性->src、url、title…语法:v-bind:属性名"表达式" 动态设置img标签的src属性: <body> <div id"app&quo…...

Pathlib操作文件IN Python
系列文章目录 文章目录 目录 系列文章目录 文章目录 前言 一、Pathlib是什么? 二、使用步骤 前言 pathlib 是 Python 标准库中用于操作文件和目录路径的模块,自 Python 3.4 起引入。它提供了一种面向对象的方式处理路径,使路径操作更加简洁、…...

AOC显示器915Sw按键失灵维修记
大家好,我是 程序员码递夫 今天给大家分享的是自己维修老古董AOC液晶显示器按键失灵的的过程,实属DIY记录。 1、引子 家里有台老古董的19寸AOC液晶显示器(型号915Sw), 一直作为我的副显示器陪伴着左右,显示还正常&a…...

霍曼转移方法介绍
霍曼转移方法介绍 背景 在航天工程中,轨道转移是指航天器从一个轨道移动到另一个轨道的过程。为了高效利用燃料并缩短转移时间,科学家们开发了多种轨道转移方法。其中,霍曼转移(Hohmann Transfer)因其燃料效率高、计…...

我的创作之路:机缘、收获、日常与未来的憧憬
目录 前言机缘收获 日常成就一个优化后的二分查找实现 憧憬 前言 每个人的成长旅程都有它独特的轨迹,而我的这段技术创作之路,则源于一次再普通不过的项目分享。 机缘 一切的开始其实是偶然。在一次项目中,我遇到了一个棘手的问题…...

《硬件架构的艺术》笔记(六):处理字节顺序
介绍 本章主要介绍字节顺序的的基本规则。(感觉偏软件了,不知道为啥那么会放进《硬件架构的艺术》这本书)。 定义 字节顺序定义数据在计算机系统中的存储格式,描述存储器中的MSB和LSB的位置。对于数据始终以32位形式保存在存储器…...

AddIPAddress添加临时IP后,socket bind失败
问题描述 在Win10\Win11下使用addIPAddress添加临时IP成功后,立即创建socket,bind失败 if(!m_socket->bind(QHostAddress(m_localIP), listenPort)) {qCritical() << QString("bind error %1").arg(m_socket->errorString());re…...

关于IDE的相关知识之一【使用技巧】
成长路上不孤单😊😊😊😊😊😊 【14后😊///C爱好者😊///持续分享所学😊///如有需要欢迎收藏转发///😊】 今日分享关于ide使用技巧的相关内容! 关于…...

线性代数在人工智能领域中的实践
一、机器学习中的线性代数应用 在机器学习中,线性代数主要用于构建和训练各种模型,如线性回归、逻辑回归、支持向量机等。这些模型在数据的特征提取、降维处理以及分类等方面发挥了重要作用。 线性回归:线性回归是最简单的机器学习算法之一…...

图片生成视频-右进
右侧进入 ffmpeg -loop 1 -i image.jpg -f lavfi -i colorcblack:s1280x720:d20 -filter_complex "[1:v]formatrgba[bg];[0:v]formatrgba,scale1280:720[img];[bg][img]overlayxif(lt(t,3),W,if(lt(t,8),W-(t-3)*W/5,0)):y(H-h)/2:enablegte(t,3)" -c:v libx264 -t 2…...

3、集线器、交换机、路由器、ip的关系。
集线器、交换机、路由器三者的关系 1、集线器2、交换机(每个交换机是不同的广播域,ip地址起到划分广播域的作用)3、 路由器4、ip地址 所有图片和资料均来源于B站:网络安全收藏家 1、集线器 一开始两台电脑通信就需要网线就可以&a…...

w~视觉~合集25
我自己的原文哦~ https://blog.51cto.com/whaosoft/12627822 #Mean Shift 简单的介绍 Mean Shift 的数学原理和代码实现,基于均值漂移法 Mean Shift 的图像分割 Mean Shift 算法简介 从分割到聚类 对于图像分割算法,一个视角就是将图像中的某些点集分为一类&a…...

Applicaiton配置文件
server:port: 8080 # 配置 Spring Boot 启动端口,默认为 8080mybatis-plus:mapper-locations: classpath:com/xtl/mapper/xml/*.xml # 指定 MyBatis Mapper XML 文件的路径,确保 MyBatis 能够正确加载 Mapper 文件global-config:db-config:id-type: au…...

(已解决)wps无法加载此加载项程序mathpage.wll
今天,在安装Mathtype的时候遇到了点问题,如图所示 尝试了网上的方法,将C:\Users\Liai_\AppData\Roaming\Microsoft\Word\STARTUP路径中的替换为32位的Mathtype加载项。但此时,word又出现了问题 后来知道了,这是因为64位…...

ubity3D基础
Unity是一个流行的游戏开发引擎,它使用C#作为其主要的编程语言。以下是一些Unity中C#编程的基础概念: • Unity编辑器: • Unity编辑器是Unity游戏引擎的核心,提供了一个可视化界面,用于创建和管理游戏项目。 • C#脚本…...

Python2和Python3的区别
和python 2.x相比,python 3.x版本在语句输出、编码、运算和异常等方面做出了一些调整,我们这篇文章就对这些调整做一个简单的介绍。 Python3.x print函数代替了print语句 在python 2.x中,输出数据使用的是print语句,例如ÿ…...

Spring框架整合单元测试
目录 一、配置文件方式 1.导入依赖 2.编写类和方法 3.配置文件applicationContext-test.xml 4.测试类 5.运行结果 二、全注解方式 1.编写类和方法 2.配置类 3.测试类 4.运行结果 每次进行单元测试的时候,都需要编写创建工厂,加载配置文件等相关…...

docker-mysql
一、创建mysql 1、docker run --name mysql8.0-container -e MYSQL_ROOT_PASSWORDmy-secret-pw -d -p 3306:3306 mysql:8.0 参数解释: --name mysql8.0-container:指定容器的名称为mysql8.0-container。 -e MYSQL_ROOT_PASSWORDmy-secret-pw:…...