golang日記ーsprint有什么用? 和+号的区别

本文探讨了Go语言中sprint和+号在字符串连接时的效率差异。sprint类似Java的StringBuilder,通过缓冲区提高性能,而+号每次连接都会创建新的字符串,对于大量拼接操作效率较低。Go语言中字符串是不可变的,这是为了内存管理和性能考虑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

刚看这段代码, 就很好奇, sprint是拿来干嘛的? 我们有了+号

name := "Todd McLeod"
str := fmt.Sprint(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
</head>
<body>
<h1>` +
name 
+`</h1>
</body>
</html>
    `)

每一种语言都有 + 号, 以操作字符串, 为什么这里不这样用呢? 我想, 可能是效率问题. 于是我找到以下的帖子
How to efficiently concatenate strings in Go?
sprint的作用就与stringbuffer差不多, 通过一个buffer储存, 从而产生高效. 那么 + 号是怎么样实现的呢?

string是固定变量, 这是无法改变的事情 , 那它导致的底层结构的变化是怎么样的?
Efficient String Concatenation in Go

为什么+号效率这么低呢? 这时, 我们应该搜operation +的原理
Efficient String Concatenation in Go2014年

This is the most obvious approach to the problem. Use the concatenate operator (+=) to append each segment to the string. The thing to know about this is that strings are immutable in Go - each time a string is assigned to a variable a new address is assigned in memory to represent the new value. This is different from languages like C++ and BASIC, where a string variable can be modified in place. In Go, each time you append to the end of a string, it must create a new string and copy the contents of both the existing string and the appended string into it. As the strings you are manipulating become large this process becomes increasingly slow. In fact, this method of naive appending is O(N2).

主要原因是, 每次相加后, 都新建String, 而且是从原字符串复制到新的String, 没有对原来的String进行利用.

Java中, +号的实现

In other words, the operator + in string concatenation is effectively a shorthand for the more verbose StringBuilder idiom.

结论: golang没有优化= =


番外:
1. golang里string是一个固定变量, 赋值后无法改变. 为什么要这样设计?
可能是因为 : 为什么String类是不可变的?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值