- This article helps to write
function
to concatenate stringarray string
->string
in the most optimal way. - Usually when writing a function to convert from
array string
to astring
, mostgolang
devs will write.
1 2 3 4 5 6 7 8 | <span class="token keyword">func</span> <span class="token function">Concat</span> <span class="token punctuation">(</span> values <span class="token punctuation">[</span> <span class="token punctuation">]</span> <span class="token builtin">string</span> <span class="token punctuation">)</span> <span class="token builtin">string</span> <span class="token punctuation">{</span> s <span class="token operator">:=</span> <span class="token string">""</span> <span class="token keyword">for</span> <span class="token boolean">_</span> <span class="token punctuation">,</span> value <span class="token operator">:=</span> <span class="token keyword">range</span> values <span class="token punctuation">{</span> s <span class="token operator">+=</span> value <span class="token punctuation">}</span> <span class="token keyword">return</span> s <span class="token punctuation">}</span> |
- The writing is not optimal, in
golang
when concatenating the string will not reuse the variables
but always create a new memory area in memory. - For optimization, there are 2 ways to write the template:
Way 1
1 2 3 4 5 6 7 8 | func Concatv2(values []string) string { sb := strings.Builder{} // (1) for _, value := range values { _, _ = sb.WriteString(value) // (2) } return sb.String() // (3) } |
- (1): create a
strings.Builder
- (2): string concatenation
- (3): return result
Way 2
1 2 3 4 5 6 7 8 9 10 11 12 13 | func Concatv3(values []string) string { total := 0 for i := 0; i < len(values); i++ { // (1) total += len(values[i]) } sb := strings.Builder{} sb.Grow(total) // (2) for _, value := range values { _, _ = sb.WriteString(value) } return sb.String() } |
- (1): loop each
string
to count the total numberbytes
. - (2): create capacity,
Grow
canpanics
, be careful when using.
Benchmark
- create file
main_test.go
, copy the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package main import "testing" var strs = []string{"b111231sdfsdfsaf21312sdafsda", "b111231sdfsdfsaf21312sdafsda", "b111231sdfsdfsaf21312sdafsda", "b111231sdfsdfsaf21312sdafsda"} func BenchmarkV1(b *testing.B) { for i := 0; i < b.N; i++ { Concat(strs) } } func BenchmarkV2(b *testing.B) { for i := 0; i < b.N; i++ { Concatv2(strs) } } func BenchmarkV3(b *testing.B) { for i := 0; i < b.N; i++ { Concatv3(strs) } } |
- execute the command:
1 2 | go test -bench=. |
1 | go test -bench=. -benchmem |