FWIW, append is most often a small performance penalty when the number of
elements is known ahead.
And for some reason, using built-in func copy, or an explicit loop, is
slightly faster on my workstation than BenchmarkConvert.
Also, "small benchmarks are hard" so I suspect the small allocations in
tight benchmark loops may not be representative of their real cost in a
real program.
func BenchmarkCopy(b *testing.B) {
for i := 0; i < b.N; i++ {
buffer := make([]byte, 3)
copy(buffer, s[:3])
prefix = string(buffer)
}
}
func BenchmarkLoop(b *testing.B) {
for i := 0; i < b.N; i++ {
buffer := make([]byte, 3)
for i := 0; i < 3; i++ {
buffer[i] = s[i]
}
prefix = string(buffer)
}
}
BenchmarkNil-4 30000000 61.9 ns/op 16 B/op
2 allocs/op
BenchmarkLiteral-4 30000000 59.6 ns/op 16 B/op
2 allocs/op
BenchmarkConvert-4 50000000 37.4 ns/op 3 B/op
1 allocs/op
BenchmarkCopy-4 50000000 30.8 ns/op 3 B/op
1 allocs/op
BenchmarkLoop-4 50000000 29.3 ns/op 3 B/op
1 allocs/op
Cheers
Val
On Tuesday, August 22, 2017 at 1:01:36 PM UTC+2, peterGo wrote:
>
> 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.