MIRROR: javascript for 🐜's, a tiny runtime with big ambitions
1// Benchmark: IC epoch hoist — measures benefit of loading the global
2// IC epoch once per function instead of once per GET_FIELD site.
3
4function bench(name, fn, iterations) {
5 const start = Date.now();
6 fn(iterations);
7 const elapsed = Date.now() - start;
8 console.log(name + ": " + elapsed + "ms (" + iterations + " iters, " + (elapsed / iterations * 1000).toFixed(2) + "µs/op)");
9}
10
11// 1. Many IC sites on the same object (wide read)
12bench("10-field single obj", function(n) {
13 let o = { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8, i: 9, j: 10 };
14 let sum = 0;
15 for (let i = 0; i < n; i++)
16 sum += o.a + o.b + o.c + o.d + o.e + o.f + o.g + o.h + o.i + o.j;
17 return sum;
18}, 2000000);
19
20// 2. Chained field access — each dot is a separate IC site
21bench("chained field 4-deep", function(n) {
22 let o = { x: { y: { z: { w: 42 } } } };
23 let sum = 0;
24 for (let i = 0; i < n; i++) sum += o.x.y.z.w;
25 return sum;
26}, 5000000);
27
28// 3. Multiple objects, multiple fields per iteration
29bench("3-obj x 3-field", function(n) {
30 let a = { x: 1, y: 2, z: 3 };
31 let b = { x: 4, y: 5, z: 6 };
32 let c = { x: 7, y: 8, z: 9 };
33 let sum = 0;
34 for (let i = 0; i < n; i++)
35 sum += a.x + a.y + a.z + b.x + b.y + b.z + c.x + c.y + c.z;
36 return sum;
37}, 2000000);
38
39// 4. Pattern matching style — branch with many IC reads
40bench("branchy multi-field", function(n) {
41 let o = { type: 1, value: 10, name: 20, data: 30, extra: 40 };
42 let sum = 0;
43 for (let i = 0; i < n; i++) {
44 if (o.type === 1)
45 sum += o.value + o.name;
46 else
47 sum += o.data + o.extra;
48 }
49 return sum;
50}, 5000000);
51
52// 5. Prototype chain with many field reads (IC + proto walk)
53bench("proto 6-field", function(n) {
54 function Point(x, y, z) { this.x = x; this.y = y; this.z = z; }
55 Point.prototype.r = 10;
56 Point.prototype.g = 20;
57 Point.prototype.b = 30;
58 let p = new Point(1, 2, 3);
59 let sum = 0;
60 for (let i = 0; i < n; i++)
61 sum += p.x + p.y + p.z + p.r + p.g + p.b;
62 return sum;
63}, 2000000);
64
65// 6. Non-loop straight-line many IC sites (function call overhead)
66function readAll(o) {
67 return o.a + o.b + o.c + o.d + o.e + o.f + o.g + o.h;
68}
69bench("call 8-field fn", function(n) {
70 let o = { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7, h: 8 };
71 let sum = 0;
72 for (let i = 0; i < n; i++) sum += readAll(o);
73 return sum;
74}, 2000000);