Valid json optimization

Added ~20% performance boost be removing extra allocation when
Valid() is called with a json string.
This commit is contained in:
tidwall 2019-02-16 14:50:53 -07:00
parent 5a96cfda70
commit 5d7556ad3d
4 changed files with 33 additions and 1 deletions

View File

@ -2038,7 +2038,7 @@ func validnull(data []byte, i int) (outi int, ok bool) {
// value := gjson.Get(json, "name.last")
//
func Valid(json string) bool {
_, ok := validpayload([]byte(json), 0)
_, ok := validpayload(stringBytes(json), 0)
return ok
}

View File

@ -8,3 +8,7 @@ func getBytes(json []byte, path string) Result {
func fillIndex(json string, c *parseContext) {
// noop. Use zero for the Index value.
}
func stringBytes(s string) []byte {
return []byte(s)
}

View File

@ -67,3 +67,11 @@ func fillIndex(json string, c *parseContext) {
}
}
}
func stringBytes(s string) []byte {
return *(*[]byte)(unsafe.Pointer(&reflect.SliceHeader{
Data: (*reflect.StringHeader)(unsafe.Pointer(&s)).Data,
Len: len(s),
Cap: len(s),
}))
}

View File

@ -1431,3 +1431,23 @@ func TestArrayValues(t *testing.T) {
}
}
func BenchmarkValid(b *testing.B) {
for i := 0; i < b.N; i++ {
Valid(complicatedJSON)
}
}
func BenchmarkValidBytes(b *testing.B) {
complicatedJSON := []byte(complicatedJSON)
for i := 0; i < b.N; i++ {
ValidBytes(complicatedJSON)
}
}
func BenchmarkGoStdlibValidBytes(b *testing.B) {
complicatedJSON := []byte(complicatedJSON)
for i := 0; i < b.N; i++ {
json.Valid(complicatedJSON)
}
}