Skip to content

Commit ee61374

Browse files
committed
fix json
1 parent 4a377d0 commit ee61374

File tree

7 files changed

+48
-28
lines changed

7 files changed

+48
-28
lines changed

samples/bench/bench.mjs

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { init as initDotNet } from "./dotnet/init.mjs";
33
import { init as initDotNetLLVM } from "./dotnet-llvm/init.mjs";
44
import { init as initGo } from "./go/init.mjs";
55
import { init as initRust } from "./rust/init.mjs";
6+
import * as fixtures from "./fixtures.mjs";
67

78
/**
89
* @typedef {Object} Exports
@@ -12,7 +13,7 @@ import { init as initRust } from "./rust/init.mjs";
1213
*/
1314

1415
const lang = process.argv[2];
15-
const baseline = [];
16+
const baseline = new Map;
1617

1718
if (!lang || lang.toLowerCase() === "rust")
1819
await run("Rust", await initRust());
@@ -29,23 +30,37 @@ if (!lang || lang.toLowerCase() === "go")
2930
* @param {Exports} exports */
3031
async function run(lang, exports) {
3132
console.log(`\n\nBenching ${lang}...\n`);
32-
console.log(`Echo number: ${iterate(0, exports.echoNumber, 100, 3, 1000)}`);
33-
console.log(`Echo struct: ${iterate(1, exports.echoStruct, 100, 3, 100)}`);
34-
console.log(`Fibonacci: ${iterate(2, () => exports.fi(33), 100, 3, 1)}`);
33+
await new Promise(r => setTimeout(r, 100));
34+
bench("Echo number", exports.echoNumber, 100, 3, 1000, fixtures.getNumber());
35+
bench("Echo struct", exports.echoStruct, 100, 3, 100, fixtures.getStruct());
36+
bench("Fibonacci", () => exports.fi(33), 100, 3, 1);
3537
}
3638

37-
function iterate(idx, fn, iterations, warms, loops) {
39+
function bench(name, fn, iters, warms, loops, expected = undefined) {
40+
if (expected) {
41+
expected = JSON.stringify(expected);
42+
const actual = JSON.stringify(fn());
43+
if (actual !== expected) {
44+
console.error(`Wrong result of '${name}'. Expected: ${expected} Actual: ${actual}`);
45+
return;
46+
}
47+
}
48+
3849
const results = [];
3950
warms *= -1;
40-
for (let i = warms; i < iterations; i++) {
51+
for (let i = warms; i < iters; i++) {
4152
const start = performance.now();
4253
for (let l = 0; l < loops; l++) fn();
4354
if (i >= 0) results.push(performance.now() - start);
4455
}
4556
let media = median(results);
46-
if (baseline[idx]) return `${(media / baseline[idx]).toFixed(1)}`;
47-
else baseline[idx] = media;
48-
return `${media.toFixed(3)} ms`;
57+
58+
if (baseline.has(name)) {
59+
console.log(`${name}: ${(media / baseline.get(name)).toFixed(1)}`);
60+
} else {
61+
baseline.set(name, media);
62+
console.log(`${name}: ${media.toFixed(3)} ms`);
63+
}
4964
}
5065

5166
function median(numbers) {

samples/bench/dotnet-llvm/Program.cs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using System;
21
using System.Runtime.InteropServices;
3-
using System.Runtime.InteropServices.JavaScript;
42
using System.Text.Json;
53
using System.Text.Json.Serialization;
64

@@ -16,7 +14,7 @@ public struct Data
1614
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
1715
internal partial class SourceGenerationContext : JsonSerializerContext;
1816

19-
public static unsafe partial class Program
17+
public static unsafe class Program
2018
{
2119
public static void Main () { }
2220

@@ -26,12 +24,16 @@ public static void Main () { }
2624
[UnmanagedCallersOnly(EntryPoint = "echoNumber")]
2725
public static int EchoNumber () => GetNumber();
2826

29-
[JSExport]
30-
public static string EchoStruct ()
27+
[UnmanagedCallersOnly(EntryPoint = "echoStruct")]
28+
public static byte* EchoStruct ()
3129
{
32-
var span = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(GetStruct());
33-
var data = JsonSerializer.Deserialize(span, SourceGenerationContext.Default.Data);
34-
return JsonSerializer.Serialize(data, SourceGenerationContext.Default.Data);
30+
var inSpan = MemoryMarshal.CreateReadOnlySpanFromNullTerminated(GetStruct());
31+
var inData = JsonSerializer.Deserialize(inSpan, SourceGenerationContext.Default.Data);
32+
var bytes = JsonSerializer.SerializeToUtf8Bytes(inData, SourceGenerationContext.Default.Data);
33+
var ptr = Marshal.AllocHGlobal(bytes.Length + 1);
34+
Marshal.Copy(bytes, 0, ptr, bytes.Length);
35+
((byte*)ptr)![bytes.Length] = 0; // add null terminator to the string
36+
return (byte*)ptr;
3537
}
3638

3739
[UnmanagedCallersOnly(EntryPoint = "fi")]

samples/bench/dotnet-llvm/init.mjs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,11 @@ import { dotnet } from "./bin/Release/net9.0-browser/browser-wasm/publish/dotnet
33
/** @returns {Promise<import("../bench.mjs").Exports>} */
44
export async function init() {
55
const runtime = await dotnet.withDiagnosticTracing(false).create();
6-
const asm = "DotNetLLVM";
7-
await runtime.runMain(asm, []);
8-
const exports = await runtime.getAssemblyExports(asm);
6+
await runtime.runMain("DotNetLLVM", []);
7+
98
return {
109
echoNumber: runtime.Module._echoNumber,
11-
echoStruct: exports.Program.EchoStruct,
10+
echoStruct: () => JSON.parse(runtime.Module.UTF8ToString(runtime.Module._echoStruct())),
1211
fi: runtime.Module._fi
1312
};
1413
}

samples/bench/dotnet/init.mjs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ export async function init() {
1616
const exports = await runtime.getAssemblyExports(asm);
1717
return {
1818
echoNumber: exports.Program.EchoNumber,
19-
echoStruct: exports.Program.EchoStruct,
19+
echoStruct: () => JSON.parse(exports.Program.EchoStruct()),
2020
fi: exports.Program.Fi
2121
};
2222
}

samples/bench/go/init.mjs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ export async function init() {
1414

1515
return {
1616
echoNumber: global.echoNumber,
17-
echoStruct: global.echoStruct,
17+
echoStruct: () => JSON.parse(global.echoStruct()),
1818
fi: global.fi
1919
};
2020
}

samples/bench/go/main.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ import (
66
)
77

88
type Data struct {
9-
Info string `json:"Info"`
10-
Ok bool `json:"Ok"`
11-
Revision int `json:"Revision"`
12-
Messages []string `json:"Messages"`
9+
Info string `json:"info"`
10+
Ok bool `json:"ok"`
11+
Revision int `json:"revision"`
12+
Messages []string `json:"messages"`
1313
}
1414

1515
func main() {

samples/bench/rust/init.mjs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,5 +5,9 @@ import { getNumber, getStruct } from "../fixtures.mjs";
55
export async function init() {
66
global.getNumber = getNumber;
77
global.getStruct = () => JSON.stringify(getStruct());
8-
return { echoNumber, echoStruct, fi };
8+
return {
9+
echoNumber,
10+
echoStruct: () => JSON.parse(echoStruct()),
11+
fi
12+
};
913
}

0 commit comments

Comments
 (0)