Files
the-way-to-go_ZH_CN/eBook/16.2.md
AutuanLiu 6d3f1902ba 修复与更正 (#337)
* Update 06.4.md

标点符号错误

* Update 06.5.md

* Update 06.6.md

* Update 06.8.md

修正上一节目录索引错误

* Update 06.8.md

* Update 07.0.md

* Update 07.1.md

* Update 07.6.md

用词不统一

* Update 08.0.md

* Update 08.6.md

用词不统一

* Update 09.0.md

* Update 09.5.md

修改不通顺

* 拼写错误

[建议加上`git remote -v`](https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/)

* Update 10.0.md

* 统一风格

* 调整位置,保证最后一行可以输出

* 保证最后一行可以输出

* 格式

* markdown 修改
2017-03-29 19:03:39 -04:00

21 lines
851 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 16.2 误用字符串
当需要对一个字符串进行频繁的操作时谨记在go语言中字符串是不可变的类似java和c#)。使用诸如`a += b`形式连接字符串效率低下,尤其在一个循环内部使用这种形式。这会导致大量的内存开销和拷贝。**应该使用一个字符数组代替字符串,将字符串内容写入一个缓存中。** 例如以下的代码示例:
```go
var b bytes.Buffer
...
for condition {
b.WriteString(str) // 将字符串str写入缓存buffer
}
return b.String()
```
注意由于编译优化和依赖于使用缓存操作的字符串大小当循环次数大于15时效率才会更佳。
## 链接
- [目录](directory.md)
- 上一节:[误用短声明导致变量覆盖](16.1.md)
- 下一节:[发生错误时使用defer关闭一个文件](16.3.md)