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

前端之家收集整理的这篇文章主要介绍了golang日記ーsprint有什么用? 和+号的区别前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

刚看这段代码,就很好奇,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类是不可变的?

猜你在找的Go相关文章