当前位置: 首页 > news >正文

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 2len+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/2m,也就是当前容量的一半都大于等于现有的内容(未读的字节数)加上所需要增加的字节数,就复用当前的数组,把未读的内容拷贝到头部去。

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 2len+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类型是不可修改的&#xff0c;对于拼接字符串来说&#xff0c;本质上还是创建一个新的对象将数据放进去。主要有以下几种拼接方式 拼接方式介绍 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布局之后&#xff0c;跳转后部分内容会被遮挡…...

easyui datagrid无数据时显示无数据

这里写自定义目录标题 需求解决办法 需求 使用datagrid显示记录时&#xff0c;结果查询记录数为0&#xff0c;此时需要显示无数据。 示例代码 <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平台】&#xff0c;以传统电商行业为基石&#xff0c;鸿鹄云商支持“商家入驻平台自营”多运营模式&#xff0c;积极打造“全新市场&#xff0c;全新 模式”企业级b2b2c电商平台&#xff0c;致力干助力各行/互联网创业腾飞并获取更多的收益。从消…...

Python AttributeError: ‘NoneType‘ object has no attribute ‘shape‘如何解决

Python AttributeError: ‘NoneType‘ object has no attribute ‘shape‘ 运行出现上述错误&#xff0c;这个错误表示某个图像对象为 NoneType &#xff0c;没有 shape 属性。通常情况下&#xff0c;这是因为 OpenCV 没有能够正确地加载图像&#xff0c;导致无法访问图像数据。…...

vue3自定义确认密码匹配验证规则

// 自定义确认密码匹配验证规则 const matchPassword (rules:any, value:any, callback:any) > {if (value ! addData.payPwd) {callback(new Error(两次密码输入不一致&#xff01;))} else {callback()} }const rules reactive({payPwd: [{ required: true, message: &q…...

岗位所处定位,岗位职责

电子产品所需岗位&#xff1a;pcb设计电路板,fpga&#xff0c;嵌入式&#xff0c;应用层&#xff08;前后端&#xff0c;移动端&#xff09;。 PCB 岗位职责&#xff1a;1.负责器件.工程或者项目与技术验证类的PCB板设计工作&#xff1b;2.协助项目中部分模块的PCB&#xff08…...

2024阿里云服务器配置推荐方案

阿里云服务器配置怎么选择合适&#xff1f;CPU内存、公网带宽和ECS实例规格怎么选择合适&#xff1f;阿里云服务器网aliyunfuwuqi.com建议根据实际使用场景选择&#xff0c;例如企业网站后台、自建数据库、企业OA、ERP等办公系统、线下IDC直接映射、高性能计算和大游戏并发&…...

OceanBase原生分布式数据库

1.历史背景 在Java Web项目中&#xff0c;常常使用免费开源的MySQL数据库存储业务数据&#xff0c;按业界经验MySQL单库超过多大数据体量&#xff0c;或单表超过几百万条数据后就会出现查询变慢的情况&#xff0c;单实例数据库只能扩展物理资源(CPU、内存)&#xff0c;来提升查…...

首次使用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.标记耦合&#xff08;特征耦合&#xff09; 6.数据耦合 7.非直接耦合 二.内聚性 1.偶然内聚 2.逻辑内聚 3.时间内聚 4.过程内聚 5.通信内聚 6.顺序内聚 7.功能内聚 一.耦合性 耦合性是指软件结构中模块相互…...

纯血鸿蒙「扩圈」100天,酝酿已久的突围

坦白讲&#xff0c;去年参加华为开发者大会看到HarmonyOS NEXT&#xff08;仅运行鸿蒙原生应用&#xff0c;所以也称作「纯血鸿蒙」&#xff09;的时候&#xff0c;小雷也没料想到鸿蒙原生应用生态的发展速度会如此之快。 9月25日&#xff0c;华为正式对外宣布启动HarmonyOS NE…...

UICollection Compositional Layout全详解

本文字数&#xff1a;8325字 预计阅读时间&#xff1a;45分钟 01 Collection View Layout全详解 UICollectionView在iOS中是构建复杂布局的强大工具。iOS13中引入的 UICollectionViewCompositionalLayout为创建自定义布局提供了全新的可能性。本文将深入探讨Compositional Lay…...

单例模式的模板

参考了网上的一些单例模式&#xff0c;自己也写一个模板。 要点&#xff1a; 线程安全性单例对象的唯一性 #include <mutex> //在模板类 Singleton 中&#xff0c;可以定义单例模式的实现细节 template <typename T> class Singleton { public://通过删除拷贝构造…...

C#基础-空处理

在c#中&#xff0c;值对象是没有办法赋值为null的。比如说&#xff0c;你想要定义一个布尔值&#xff0c;你的赋值数据要么得是true、要么就得是false&#xff0c;默认情况下我们永远没可能给这个布尔赋值为null&#xff0c;即使只是对这个变量进行声明而不初始化数据&#xff…...

测试平台开发vue组件化重构前端代码

基于 springbootvue 的测试平台开发 继续更新&#xff08;人在魔都 T_T&#xff09;。 这期其实并不是一个详细的开发过程记录&#xff0c;主要还是针对本次前端重构来聊聊几个关注点。 目前重构的总进度在80%&#xff0c;重构完的页面没什么变化&#xff0c;再回顾一下。 一…...

龍运当头--html做一个中国火龙祝大家龙年大吉

🐉效果展示 🐉HTML展示 <body> <!-- partial:index.partial.html --> <svg><defs><g id=...

Dockerfile语法和简单镜像构建

Dockerfile是一个用于定义Docker镜像的文本文件&#xff0c;包含了一系列的指令和参数&#xff0c;用于指示Docker在构建镜像时应该执行哪些操作&#xff0c;例如基于哪个基础镜像、复制哪些文件到镜像中、运行哪些命令等。 Dockerfile文件的内容主要有几个部分组成&#xff0c…...

uniapp使用wxml-to-canvas开发小程序保存canvas图片

微信小程序官方解决方案&#xff1a;wxml-to-canvas 使用wxml-to-canvas要知道一些前提条件 1、只能画view&#xff0c;text&#xff0c;image 2、每个元素必须要设置宽高 3、默认是flex布局&#xff0c;可以通过flexDirection: "column"来改变排列方式 4、文字 必…...

RestClient

什么是RestClient RestClient 是 Elasticsearch 官方提供的 Java 低级 REST 客户端&#xff0c;它允许HTTP与Elasticsearch 集群通信&#xff0c;而无需处理 JSON 序列化/反序列化等底层细节。它是 Elasticsearch Java API 客户端的基础。 RestClient 主要特点 轻量级&#xff…...

【Axure高保真原型】引导弹窗

今天和大家中分享引导弹窗的原型模板&#xff0c;载入页面后&#xff0c;会显示引导弹窗&#xff0c;适用于引导用户使用页面&#xff0c;点击完成后&#xff0c;会显示下一个引导弹窗&#xff0c;直至最后一个引导弹窗完成后进入首页。具体效果可以点击下方视频观看或打开下方…...

铭豹扩展坞 USB转网口 突然无法识别解决方法

当 USB 转网口扩展坞在一台笔记本上无法识别,但在其他电脑上正常工作时,问题通常出在笔记本自身或其与扩展坞的兼容性上。以下是系统化的定位思路和排查步骤,帮助你快速找到故障原因: 背景: 一个M-pard(铭豹)扩展坞的网卡突然无法识别了,扩展出来的三个USB接口正常。…...

Android Bitmap治理全解析:从加载优化到泄漏防控的全生命周期管理

引言 Bitmap&#xff08;位图&#xff09;是Android应用内存占用的“头号杀手”。一张1080P&#xff08;1920x1080&#xff09;的图片以ARGB_8888格式加载时&#xff0c;内存占用高达8MB&#xff08;192010804字节&#xff09;。据统计&#xff0c;超过60%的应用OOM崩溃与Bitm…...

蓝桥杯3498 01串的熵

问题描述 对于一个长度为 23333333的 01 串, 如果其信息熵为 11625907.5798&#xff0c; 且 0 出现次数比 1 少, 那么这个 01 串中 0 出现了多少次? #include<iostream> #include<cmath> using namespace std;int n 23333333;int main() {//枚举 0 出现的次数//因…...

今日学习:Spring线程池|并发修改异常|链路丢失|登录续期|VIP过期策略|数值类缓存

文章目录 优雅版线程池ThreadPoolTaskExecutor和ThreadPoolTaskExecutor的装饰器并发修改异常并发修改异常简介实现机制设计原因及意义 使用线程池造成的链路丢失问题线程池导致的链路丢失问题发生原因 常见解决方法更好的解决方法设计精妙之处 登录续期登录续期常见实现方式特…...

基于Java Swing的电子通讯录设计与实现:附系统托盘功能代码详解

JAVASQL电子通讯录带系统托盘 一、系统概述 本电子通讯录系统采用Java Swing开发桌面应用&#xff0c;结合SQLite数据库实现联系人管理功能&#xff0c;并集成系统托盘功能提升用户体验。系统支持联系人的增删改查、分组管理、搜索过滤等功能&#xff0c;同时可以最小化到系统…...

VM虚拟机网络配置(ubuntu24桥接模式):配置静态IP

编辑-虚拟网络编辑器-更改设置 选择桥接模式&#xff0c;然后找到相应的网卡&#xff08;可以查看自己本机的网络连接&#xff09; windows连接的网络点击查看属性 编辑虚拟机设置更改网络配置&#xff0c;选择刚才配置的桥接模式 静态ip设置&#xff1a; 我用的ubuntu24桌…...

第7篇:中间件全链路监控与 SQL 性能分析实践

7.1 章节导读 在构建数据库中间件的过程中&#xff0c;可观测性 和 性能分析 是保障系统稳定性与可维护性的核心能力。 特别是在复杂分布式场景中&#xff0c;必须做到&#xff1a; &#x1f50d; 追踪每一条 SQL 的生命周期&#xff08;从入口到数据库执行&#xff09;&#…...

面试高频问题

文章目录 &#x1f680; 消息队列核心技术揭秘&#xff1a;从入门到秒杀面试官1️⃣ Kafka为何能"吞云吐雾"&#xff1f;性能背后的秘密1.1 顺序写入与零拷贝&#xff1a;性能的双引擎1.2 分区并行&#xff1a;数据的"八车道高速公路"1.3 页缓存与批量处理…...