rogchap / v8go

Execute JavaScript from Go

Home Page:https://rogchap.com/v8go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Can we use standard library encoding/json?

renanbastos93 opened this issue · comments

I believe that by using the standard library we can gain better performance.

I created a little example

func ExampleJSONStringify2() {
	var JSON string
	b, _ := json.Marshal(`{
		"a": 1,
		"b": "foo"
	}`)
	_ = json.Unmarshal(b, &JSON)
}

BenchmarkTest

func BenchmarkTestJSONStringify(b *testing.B) {
	for i := 0; i < b.N; i++ {
		ExampleJSONStringify2()
	}
}

Output: BenchmarkTestJSONStringify-8 1564982 769.6 ns/op 304 B/op 5 allocs/op

Original function

func ExampleJSONStringify() {
	ctx := v8.NewContext()
	defer ctx.Isolate().Dispose()
	defer ctx.Close()
	val, _ := v8.JSONParse(ctx, `{
		"a": 1,
		"b": "foo"
	}`)
	_, _ = v8.JSONStringify(ctx, val)
	// fmt.Println(jsonStr)
	// Output:
	// {"a":1,"b":"foo"}
}

BenchmarkTest

func BenchmarkTestJSONStringify(b *testing.B) {
	for i := 0; i < b.N; i++ {
		ExampleJSONStringify()
	}
}

Output: BenchmarkTestJSONStringify-8 612 1917574 ns/op 360 B/op 21 allocs/op

Maybe I don't know exactly what method in lib C did then we can rewrite it together and improve this package. What do you think?

You are benchmarking deserialization with serialization. If you just want to normalize JSON, then I agree that there is no point in using this library. The point of using v8go.JSONParse would be to create V8 objects, so no further conversion is needed to pass them into V8.