> For the complete documentation index, see [llms.txt](https://ryanyang.gitbook.io/the-way-to-go-zh-cn/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ryanyang.gitbook.io/the-way-to-go-zh-cn/di-si-bu-fen-shi-ji-ying-yong/18.0/18.11.md).

# 出于性能考虑的最佳实践和建议

（1）尽可能的使用`:=`去初始化声明一个变量（在函数内部）；

（2）尽可能的使用字符代替字符串；

（3）尽可能的使用切片代替数组；

（4）尽可能的使用数组和切片代替映射（详见参考文献15）；

（5）如果只想获取切片中某项值，不需要值的索引，尽可能的使用`for range`去遍历切片，这比必须查询切片中的每个元素要快一些；

（6）当数组元素是稀疏的（例如有很多`0`值或者空值`nil`），使用映射会降低内存消耗；

（7）初始化映射时指定其容量；

（8）当定义一个方法时，使用指针类型作为方法的接受者；

（9）在代码中使用常量或者标志提取常量的值；

（10）尽可能在需要分配大量内存时使用缓存；

（11）使用缓存模板（参考[章节15.7](https://github.com/yangchuansheng/the-way-to-go_ZH_CN/tree/f30ab7d8c58f85840a0afb548024b93642b518d5/eBook/15.7.md)）。

## 链接

* [目录](https://github.com/yangchuansheng/the-way-to-go_ZH_CN/tree/f30ab7d8c58f85840a0afb548024b93642b518d5/eBook/directory.md)
* 上一节：[其他](/the-way-to-go-zh-cn/di-si-bu-fen-shi-ji-ying-yong/18.0/18.10.md)
* 下一章：[构建一个完整的应用程序](https://github.com/yangchuansheng/the-way-to-go_ZH_CN/tree/f30ab7d8c58f85840a0afb548024b93642b518d5/eBook/19.0.md)
