Last active
September 7, 2016 06:32
-
-
Save ssttevee/792043637a1c850ed26e06acf6aef3c9 to your computer and use it in GitHub Desktop.
testing string reversals
This file contains hidden or 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 tests | |
// RESULTS | |
// | |
// Benchmark_Reveral_Buffer-4 3000000 507 ns/op | |
// Benchmark_Reveral_Concat-4 500000 3703 ns/op | |
// Benchmark_Reversal_Append-4 300000 4496 ns/op | |
import ( | |
"testing" | |
"bytes" | |
) | |
var subject = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
var reversed = "ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihgfedcba9876543210" | |
func Reversal_Buffer(s string) string { | |
var ret bytes.Buffer | |
for i := len(s); i > 0; i-- { | |
ret.WriteByte(s[i-1]) | |
} | |
return ret.String() | |
} | |
func Reversal_Concat(s string) string { | |
var ret string | |
for i := 0; i < len(s); i++ { | |
ret = s[i:i+1] + ret | |
} | |
return ret | |
} | |
func Reversal_Append(s string) string { | |
var ret []byte | |
for i := 0; i < len(s); i++ { | |
ret = append([]byte{s[i]}, ret...) | |
} | |
return string(ret) | |
} | |
func Test_Reversal_Buffer(t *testing.T) { | |
if Reversal_Buffer(subject) != reversed { | |
t.Error("bad reversal") | |
} | |
} | |
func Test_Reversal_Concat(t *testing.T) { | |
if Reversal_Concat(subject) != reversed { | |
t.Error("bad reversal") | |
} | |
} | |
func Test_Reversal_Append(t *testing.T) { | |
if Reversal_Append(subject) != reversed { | |
t.Error("bad reversal") | |
} | |
} | |
func Benchmark_Reveral_Buffer(b *testing.B) { | |
for n := 0; n < b.N; n++ { | |
Reversal_Buffer(subject) | |
} | |
} | |
func Benchmark_Reveral_Concat(b *testing.B) { | |
for n := 0; n < b.N; n++ { | |
Reversal_Concat(subject) | |
} | |
} | |
func Benchmark_Reversal_Append(b *testing.B) { | |
for n := 0; n < b.N; n++ { | |
Reversal_Append(subject) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment