GoLang中拼接字符串性能优化方法详解
作者:raoxiaoya 时间:2024-04-28 09:16:46
字符串在内存中是不可变的,放在只读内存段,因此你可以使用str[0]
来访问,但是不能使用str[0]='a'
来修改。
修改字符串实际上是重新放入新的地址,因此拼接字符串可能出现的性能问题就是频繁的内存分配,比如:
func s1(ids []string) (s string) {
for _, id := range ids {
s += id
}
return
}
在golang中,具有预先分配内存特性的是切片,如果预先就分配好内存,然后再依次将字符串装进去就避免了内存的频繁分配。
再来看看strings
包的实现
func Join(elems []string, sep string) string {
switch len(elems) {
case 0:
return ""
case 1:
return elems[0]
}
n := len(sep) * (len(elems) - 1)
for i := 0; i < len(elems); i++ {
n += len(elems[i])
}
var b Builder
b.Grow(n)
b.WriteString(elems[0])
for _, s := range elems[1:] {
b.WriteString(sep)
b.WriteString(s)
}
return b.String()
}
主要就用到strings.Builder
对象,它包含一个切片。
type Builder struct {
addr *Builder // of receiver, to detect copies by value
buf []byte
}
Builder
的Grow
方法就是主动扩容切片的容积。
// 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
}
// Grow grows b's capacity, if necessary, to guarantee space for
// another n bytes. After Grow(n), at least n bytes can be written to b
// without another allocation. If n is negative, Grow panics.
func (b *Builder) Grow(n int) {
b.copyCheck()
if n < 0 {
panic("strings.Builder.Grow: negative count")
}
if cap(b.buf)-len(b.buf) < n {
b.grow(n)
}
}
来源:https://blog.csdn.net/raoxiaoya/article/details/124629601
标签:GoLang,拼接,字符串
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python 处理dataframe中的时间字段方法
2021-04-27 05:21:33
详尽讲述用Python的Django框架测试驱动开发的教程
2023-04-21 18:28:19
![](https://img.aspxhome.com/file/2023/1/75921_0s.png)
Python实现删除文件中含“指定内容”的行示例
2022-01-15 02:56:28
python去掉行尾的换行符方法
2021-10-24 02:36:22
python实现整数的二进制循环移位
2022-09-08 23:11:39
![](https://img.aspxhome.com/file/2023/1/97681_0s.jpg)
ASP 内建六大对象简介
2009-06-04 18:08:00
Python lambda 匿名函数优点和局限性深度总结
2023-07-25 19:22:00
python多进程程序打包成exe的问题
2023-08-07 13:39:03
MySQL和MongoDB设计实例对比
2011-06-19 15:41:01
PHP用PDO如何封装简单易用的DB类详解
2023-11-23 16:05:39
![](https://img.aspxhome.com/file/2023/2/104172_0s.png)
python利用多线程+队列技术爬取中介网互联网网站排行榜
2023-05-19 08:17:21
![](https://img.aspxhome.com/file/2023/9/114619_0s.webp)
Python识别快递条形码及Tesseract-OCR使用详解
2022-10-20 01:32:32
![](https://img.aspxhome.com/file/2023/8/125888_0s.jpg)
详解Scrapy Redis入门实战
2023-04-14 11:39:08
![](https://img.aspxhome.com/file/2023/1/76111_0s.png)
不要用强制方法杀掉python线程
2021-04-10 09:19:18
由不同的索引更新解决MySQL死锁套路
2024-01-18 02:03:53
![](https://img.aspxhome.com/file/2023/5/121585_0s.jpg)
Python基于hashlib模块的文件MD5一致性加密验证示例
2022-03-30 12:05:40
在Python中通过机器学习实现人体姿势估计
2022-05-20 13:08:25
![](https://img.aspxhome.com/file/2023/0/127650_0s.png)
Python中的多线程实例(简单易懂)
2021-12-07 04:09:47
![](https://img.aspxhome.com/file/2023/7/80447_0s.png)
python开发游戏的前期准备
2022-01-06 12:58:01
![](https://img.aspxhome.com/file/2023/5/99175_0s.png)
提高MySQL查询效率的三个技巧
2009-02-11 13:19:00