forked from mirror/gjson
Valid json optimization
Added ~20% performance boost be removing extra allocation when Valid() is called with a json string.
This commit is contained in:
parent
5a96cfda70
commit
5d7556ad3d
2
gjson.go
2
gjson.go
|
@ -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
|
||||
}
|
||||
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
|
@ -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),
|
||||
}))
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue