Last active
July 28, 2018 23:38
-
-
Save orasik/eb1a9c18a3274ce5ab2794358c84b2b5 to your computer and use it in GitHub Desktop.
Go string vs buffer vs strings builder timings
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 ( | |
"strings" | |
"bytes" | |
"fmt" | |
"time" | |
) | |
const Loops= 10000 | |
func main() { | |
withBuffer() | |
withStringsBuilder() | |
withoutBuffer() | |
} | |
func withoutBuffer() { | |
start := time.Now() | |
var a string | |
for i := 0; i < Loops; i++ { | |
a += "Hello " | |
} | |
elapsedTime := time.Since(start) | |
fmt.Println("Running without Buffer ...") | |
fmt.Println(elapsedTime) | |
} | |
func withBuffer() { | |
start := time.Now() | |
var b bytes.Buffer | |
for i := 0; i < Loops; i++ { | |
b.WriteString("Hello ") | |
} | |
elapsedTime := time.Since(start) | |
fmt.Println("Running with Buffer ...") | |
fmt.Println(elapsedTime) | |
} | |
func withStringsBuilder() { | |
start := time.Now() | |
var b strings.Builder | |
for i := 0; i < Loops; i++ { | |
b.WriteString("Hello ") | |
} | |
elapsedTime := time.Since(start) | |
fmt.Println("Running with Strings Builder ...") | |
fmt.Println(elapsedTime) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment