A benchmark;
https://play.golang.org/p/oUyeldDG5Q
$ cat strslice_test.go
package main
import (
"strings"
"testing"
)
var (
s = strings.Repeat("a very, very long string", 4096)
prefix string
)
func BenchmarkNil(b *testing.B) {
for i := 0; i < b.N; i++ {
prefix = string(append([]byte(nil), s[:3]...))
}
}
func BenchmarkLiteral(b *testing.B) {
for i := 0; i < b.N; i++ {
prefix = string(append([]byte{}, s[:3]...))
}
}
func BenchmarkConvert(b *testing.B) {
for i := 0; i < b.N; i++ {
prefix = string([]byte(s[:3]))
}
}
$ go test -run=! -bench=. -benchmem strslice_test.go
goos: linux
goarch: amd64
BenchmarkNil-4 10000000 174 ns/op 16 B/op
2 allocs/op
BenchmarkLiteral-4 10000000 174 ns/op 16 B/op
2 allocs/op
BenchmarkConvert-4 20000000 77.0 ns/op 3 B/op
1 allocs/op
PASS
ok command-line-arguments 5.512s
$
Peter
On Tuesday, August 22, 2017 at 12:15:44 AM UTC-4, Tamás Gulácsi wrote:
>
> prefix := string([]byte(verylongstring[:3]))
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.