Skip to content

Commit

Permalink
Use strings.Replacer to allocate Replace up front instead of in each …
Browse files Browse the repository at this point in the history
…loop iteration. (#126)

* Switch json module to go-json.

 - Use strings.Replacer instead of strings.Replace

* Remove go-json and use encoding/json

* Remove go-json from gabs.go

---------

Co-authored-by: Steve McDaniel <[email protected]>
Co-authored-by: Steve McDaniel <[email protected]>
Co-authored-by: Ashley Jeffs <[email protected]>
  • Loading branch information
4 people authored Feb 14, 2023
1 parent 7762b59 commit 08a5d6f
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
18 changes: 12 additions & 6 deletions gabs.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,16 @@ var (
ErrInvalidBuffer = errors.New("input buffer contained invalid JSON")
)

var (
r1 *strings.Replacer
r2 *strings.Replacer
)

func init() {
r1 = strings.NewReplacer("~1", "/", "~0", "~")
r2 = strings.NewReplacer("~1", ".", "~0", "~")
}

//------------------------------------------------------------------------------

// JSONPointerToSlice parses a JSON pointer path
Expand All @@ -97,9 +107,7 @@ func JSONPointerToSlice(path string) ([]string, error) {
}
hierarchy := strings.Split(path, "/")[1:]
for i, v := range hierarchy {
v = strings.ReplaceAll(v, "~1", "/")
v = strings.ReplaceAll(v, "~0", "~")
hierarchy[i] = v
hierarchy[i] = r1.Replace(v)
}
return hierarchy, nil
}
Expand All @@ -112,9 +120,7 @@ func JSONPointerToSlice(path string) ([]string, error) {
func DotPathToSlice(path string) []string {
hierarchy := strings.Split(path, ".")
for i, v := range hierarchy {
v = strings.ReplaceAll(v, "~1", ".")
v = strings.ReplaceAll(v, "~0", "~")
hierarchy[i] = v
hierarchy[i] = r2.Replace(v)
}
return hierarchy
}
Expand Down
2 changes: 2 additions & 0 deletions gabs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1578,6 +1578,7 @@ dynamic approach.
*/

func BenchmarkStatic(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
var jsonObj jsonStructure
if err := json.Unmarshal(jsonContent, &jsonObj); err != nil {
Expand All @@ -1603,6 +1604,7 @@ func BenchmarkStatic(b *testing.B) {
}

func BenchmarkDynamic(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
jsonObj, err := ParseJSON(jsonContent)
if err != nil {
Expand Down

0 comments on commit 08a5d6f

Please sign in to comment.