Instantly share code, notes, and snippets.

Embed
What would you like to do?
package bench
import (
"strings"
"testing"
)
func recursiveFindKeyStack(searchKey string, recursiveMap map[string]interface{}) []interface{} {
targets := []map[string]interface{}{
recursiveMap,
}
var results []interface{}
for {
target := targets[0]
if val, ok := target[searchKey]; ok {
results = append(results, val)
}
for _, v := range target {
if child, ok := v.(map[string]interface{}); ok {
targets = append(targets, child)
}
}
targetsLength := len(targets)
if targetsLength == 1 {
break
}
targets = targets[1:targetsLength]
}
return results
}
func recursiveFindKeyCall(searchKey string, recursiveMap map[string]interface{}) []interface{} {
var results []interface{}
if val, ok := recursiveMap[searchKey]; ok {
results = append(results, val)
}
for _, v := range recursiveMap {
if child, ok := v.(map[string]interface{}); ok {
for _, r := range recursiveFindKeyCall(searchKey, child) {
results = append(results, r)
}
}
}
return results
}
var searchkey string
var target map[string]interface{}
var expect []interface{}
func init() {
searchkey = "a"
charrange := strings.Split("0123456789", "")
tmp := map[string]interface{}{
"a": "test",
}
target = map[string]interface{}{}
for _, top := range charrange {
at := map[string]interface{}{}
for _, a := range charrange {
bt := map[string]interface{}{}
for _, b := range charrange {
ct := map[string]interface{}{}
for _, c := range charrange {
dt := map[string]interface{}{}
for _, d := range charrange {
et := map[string]interface{}{}
for _, e := range charrange {
et[e] = tmp
}
dt[d] = et
}
dt["@"] = tmp
ct[c] = dt
}
ct["@"] = tmp
bt[b] = ct
}
bt["@"] = tmp
at[a] = bt
}
at["@"] = tmp
target[top] = at
}
target["@"] = tmp
expect = []interface{}{}
for i := 0; i < 1011111; i++ {
expect = append(expect, "test")
}
}
func check(b *testing.B, result []interface{}) {
if len(result) != len(expect) {
b.Fatalf("logic failed, %d, %d", len(result), len(expect))
}
// // if need compare values
// rJson, err := json.Marshal(result)
// if err != nil {
// b.Fatal("logic failed")
// }
//
// eJson, err := json.Marshal(expect)
// if err != nil {
// b.Fatal("logic failed")
// }
//
// if string(rJson) != string(eJson) {
// b.Fatalf("logic failed, wants %s, got %s", string(eJson), string(rJson))
// }
}
func BenchmarkRecursiveCall(b *testing.B) {
check(b, recursiveFindKeyCall(searchkey, target))
}
func BenchmarkStack(b *testing.B) {
check(b, recursiveFindKeyStack(searchkey, target))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment