MIRROR: javascript for 馃悳's, a tiny runtime with big ambitions
1// Benchmark: interpreter fallback-call overhead.
2//
3// This targets the paths in silver/engine.c that call sv_vm_call(...) and then
4// continue executing in the current frame. It is useful for tracking the cost
5// of refreshing cached frame/stack locals after re-entrant native calls.
6
7const now =
8 typeof performance !== "undefined" && performance && typeof performance.now === "function"
9 ? () => performance.now()
10 : () => Date.now();
11
12let sink = 0;
13
14function bench(name, iterations, fn) {
15 for (let i = 0; i < 3; i++) fn(iterations >> 3 || 1);
16
17 const start = now();
18 const ops = fn(iterations);
19 const elapsed = now() - start;
20 const nsPerOp = (elapsed * 1e6) / ops;
21 const opsPerSec = (ops * 1000) / elapsed;
22
23 console.log(
24 name +
25 ": " +
26 elapsed.toFixed(2) +
27 "ms (" +
28 ops +
29 " ops, " +
30 nsPerOp.toFixed(2) +
31 " ns/op, " +
32 opsPerSec.toFixed(0) +
33 " ops/s)"
34 );
35}
36
37function jsAdd(a, b) {
38 return a + b;
39}
40
41bench("js direct call", 5000000, function(n) {
42 let sum = 0;
43 for (let i = 0; i < n; i++) sum += jsAdd(i, 1);
44 sink = sum;
45 return n;
46});
47
48bench("native method Math.abs", 5000000, function(n) {
49 let sum = 0;
50 for (let i = 0; i < n; i++) sum += Math.abs(-i);
51 sink = sum;
52 return n;
53});
54
55bench("native method Math.imul", 5000000, function(n) {
56 let sum = 0;
57 for (let i = 0; i < n; i++) sum += Math.imul(i, 3);
58 sink = sum;
59 return n;
60});
61
62bench("native method array push/pop", 3000000, function(n) {
63 const arr = [];
64 let sum = 0;
65 for (let i = 0; i < n; i++) {
66 arr.push(i);
67 sum += arr.pop();
68 }
69 sink = sum + arr.length;
70 return n * 2;
71});
72
73bench("native method string charCodeAt", 5000000, function(n) {
74 const str = "fallback";
75 let sum = 0;
76 for (let i = 0; i < n; i++) sum += str.charCodeAt(i & 7);
77 sink = sum;
78 return n;
79});
80
81bench("native method Date.now", 1000000, function(n) {
82 let sum = 0;
83 for (let i = 0; i < n; i++) sum += Date.now() & 1;
84 sink = sum;
85 return n;
86});
87
88console.log("sink:", sink);