Created
June 27, 2023 18:22
-
-
Save ehfeng/bce87ffd91c46f7de9c84e975e405fcb to your computer and use it in GitHub Desktop.
Performance cost of slightly complicated function call
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"runtime" | |
"sync" | |
"time" | |
v8 "rogchap.com/v8go" | |
) | |
func generateJSON(size int) string { | |
result := []map[string]string{} | |
for i := 0; i < size; i++ { | |
result = append(result, map[string]string{ | |
"key": fmt.Sprintf("value-%d", i), | |
"another-key": fmt.Sprintf("another-value-%d", i), | |
}) | |
} | |
b, err := json.Marshal(result) | |
if err != nil { | |
panic(err) | |
} | |
return string(b) | |
} | |
// must be a list of >5 length | |
func startIsolatesInParallel(n int, json string) { | |
var wg sync.WaitGroup | |
for i := 0; i < n; i++ { | |
wg.Add(1) | |
go func() { | |
runtime.LockOSThread() | |
defer runtime.UnlockOSThread() | |
isolate := v8.NewIsolate() | |
defer isolate.Dispose() | |
ctx := v8.NewContext(isolate) | |
fnV, err := ctx.RunScript(`json => {const i = 124 - 121; return "hello" + json[i].key + json[4]["another-key"]}`, "") | |
if err != nil { | |
panic(err) | |
} | |
fn, err := fnV.AsFunction() | |
if err != nil { | |
panic(err) | |
} | |
v, err := v8.JSONParse(ctx, json) | |
if err != nil { | |
panic(err) | |
} | |
defer v.Release() | |
fnStart := time.Now() | |
_, err = fn.Call(v8.Undefined(isolate), v) | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("fn call", time.Since(fnStart)) | |
wg.Done() | |
}() | |
} | |
wg.Wait() | |
} | |
func main() { | |
var start time.Time | |
start = time.Now() | |
isolate := v8.NewIsolate() | |
v8.NewContext(isolate) | |
isolate.Dispose() | |
fmt.Println("Warmup:", time.Since(start)) | |
startIsolatesInParallel(1, generateJSON(10)) | |
startIsolatesInParallel(1, generateJSON(10)) | |
startIsolatesInParallel(1, generateJSON(100)) | |
startIsolatesInParallel(1, generateJSON(1000)) | |
startIsolatesInParallel(1, generateJSON(10000)) | |
} | |
// Warmup: 6.587459ms | |
// fn call 114.584µs | |
// fn call 20.541µs | |
// fn call 20.625µs | |
// fn call 18.167µs | |
// fn call 24.625µs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment