Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 898e89a

Browse files
4.1 行内拼接字符串推荐使用运算符+
1 parent 90bb2db commit 898e89a

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package datastructure
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
)
7+
8+
/**
9+
从性能出发,兼顾易用可读,如果待拼接的变量不涉及类型转换且数量较少(<=5),行内拼接字符串推荐使用运算符 +,反之使用 fmt.Sprintf()。
10+
*/
11+
12+
// Good
13+
func BenchmarkJoinStrWithOperator(b *testing.B) {
14+
s1, s2, s3 := "foo", "bar", "baz"
15+
for i := 0; i < b.N; i++ {
16+
_ = s1 + s2 + s3
17+
}
18+
}
19+
20+
// Bad
21+
func BenchmarkJoinStrWithSprintf(b *testing.B) {
22+
s1, s2, s3 := "foo", "bar", "baz"
23+
for i := 0; i < b.N; i++ {
24+
_ = fmt.Sprintf("%s%s%s", s1, s2, s3)
25+
}
26+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
![carbon (1)](https://raw.githubusercontent.com/boatrainlsz/my-image-hosting/main/202203181455261.svg)

‎performance_rule/readme.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,5 +54,10 @@ cpu: AMD Ryzen 5 4600U with Radeon Graphics
5454
| ------------------------------------------------------------ | ------------------------------------------------------------ |
5555
| [slice_capacity_test.go](datastructure/slice_capacity_test.go) | [slice_capacity_test.md](datastructure/slice_capacity_test.md) |
5656

57+
### 4. 字符串拼接方式的选择
5758

59+
#### 4.1 行内拼接字符串推荐使用运算符+
5860

61+
| 代码 | 验证结果 |
62+
| -------------------------------------------------- | -------------------------------------------------- |
63+
| [join_str_test.go](datastructure/join_str_test.go) | [join_str_test.md](datastructure/join_str_test.md) |

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /