-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #147 from jjjjjim/master
Tip #35 转换字符串时优先使用 strconv 而非 fmt
- Loading branch information
Showing
6 changed files
with
28 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
# Tip #35 转换字符串时优先使用 strconv 而非 fmt | ||
|
||
> 原始链接:[Golang Tip #35: Prefer strconv over fmt for converting to/from string.](https://twitter.com/func25/status/1763187911942660330) | ||
> | ||
当需要将数字转换为字符串时,选择合适的工具可以加快处理速度。 | ||
|
||
**strconv** 包专门为这个场景而设计,每一点性能提升和内存节省都很重要。 | ||
|
||
我们来看一个简单的基准测试: | ||
|
||
![](./images/035/035_01.png) | ||
|
||
基准测试显示出显着的性能差异。 | ||
|
||
![](./images/035/035_02.png) | ||
|
||
*(虽然我不确定编译器是否做了优化,但两者的上下文是相同的)* | ||
|
||
- **strconv** 的函数是为特定的转换任务设计的,这使得它们能比更通用的 **fmt** 函数执行得更快。 | ||
- **fmt.Sprint** 函数及其变体需要通过反射来识别其正在处理的类型,并确定如何将其格式化为字符串。 | ||
|
||
![](./images/035/035_03.png) | ||
|
||
这个反射过程并非无成本,它既增加了时间也增加了内存开销。 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.