Last active
January 20, 2023 02:37
-
-
Save func25/bfa37fe6bbce9e59ee343c55b4fa6ae8 to your computer and use it in GitHub Desktop.
Comparing between string and byte buffer in golang
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
package main | |
import ( | |
"bytes" | |
"fmt" | |
"strings" | |
"time" | |
) | |
func main() { | |
// String concatenation | |
start := time.Now() | |
s := "" | |
for i := 0; i < 100000; i++ { | |
s += "x" | |
} | |
elapsed := time.Since(start) | |
fmt.Printf("String concatenation: %s\n", elapsed) // String concatenation: 448.49125ms | |
// bytes.Buffer | |
start = time.Now() | |
var buffer bytes.Buffer | |
for i := 0; i < 100000; i++ { | |
buffer.WriteString("x") | |
} | |
s = buffer.String() | |
elapsed = time.Since(start) | |
fmt.Printf("bytes.Buffer: %s\n", elapsed) // bytes.Buffer: 1.66225ms | |
// string.Builder | |
start = time.Now() | |
var builder strings.Builder | |
for i := 0; i < 100000; i++ { | |
builder.WriteString("x") | |
} | |
s = builder.String() | |
elapsed = time.Since(start) | |
fmt.Printf("strings.Builder: %s\n", elapsed) // string.Builder: 1.097833ms | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment