Created
August 3, 2018 16:43
-
-
Save titpetric/277391ff1880c3750d5e9f543640afec to your computer and use it in GitHub Desktop.
Illustrated example of poor implementation (memory use)
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" | |
"testing" | |
) | |
func BenchmarkStringReverseBad(b *testing.B) { | |
b.ReportAllocs() | |
input := "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." | |
for i := 0; i < b.N; i++ { | |
words := strings.Split(input, " ") | |
wordsReverse := make([]string, 0) | |
for { | |
word := words[len(words)-1:][0] | |
wordsReverse = append(wordsReverse, word) | |
words = words[:len(words)-1] | |
if len(words) == 0 { | |
break | |
} | |
} | |
output := strings.Join(wordsReverse, " ") | |
if output != "difficulty. every in opportunity the sees optimist an opportunity; every in difficulty the sees pessimist A" { | |
b.Error("Unexpected result: " + output) | |
} | |
} | |
} | |
func BenchmarkStringReverseBetter(b *testing.B) { | |
b.ReportAllocs() | |
input := "A pessimist sees the difficulty in every opportunity; an optimist sees the opportunity in every difficulty." | |
for i := 0; i < b.N; i++ { | |
words := strings.Split(input, " ") | |
for i := 0; i < len(words)/2; i++ { | |
words[len(words)-1-i], words[i] = words[i], words[len(words)-1-i] | |
} | |
output := strings.Join(words, " ") | |
if output != "difficulty. every in opportunity the sees optimist an opportunity; every in difficulty the sees pessimist A" { | |
b.Error("Unexpected result: " + output) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment