typenative 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/.github/workflows/ci.yml +2 -2
  2. package/.github/workflows/npm-publish-github-packages.yml +2 -2
  3. package/CHANGELOG.md +271 -1
  4. package/CONTRIBUTION.md +2 -1
  5. package/README.md +15 -7
  6. package/bin/cli.js +1 -0
  7. package/bin/index.js +62 -3
  8. package/bin/main.js +1 -0
  9. package/bin/node/core.js +41 -0
  10. package/bin/node/events.js +15 -10
  11. package/bin/node/process.js +13 -0
  12. package/bin/node/punycode.js +2 -2
  13. package/bin/node/timers.js +4 -2
  14. package/bin/node/url.js +1 -1
  15. package/bin/parse-node.js +2 -2
  16. package/bin/regex_vm.js +2057 -0
  17. package/bin/transpiler.js +17225 -4830
  18. package/bin/typecheck-node.js +2 -1
  19. package/bin/version.js +1 -1
  20. package/conformance.md +57 -15
  21. package/examples/README.md +46 -23
  22. package/examples/angular-templates/README.md +139 -0
  23. package/examples/angular-templates/bench.mjs +173 -0
  24. package/examples/angular-templates/dom-type-globals.d.ts +21 -0
  25. package/examples/angular-templates/dom-type-stubs.ts +21 -0
  26. package/examples/angular-templates/main.ts +135 -0
  27. package/examples/angular-templates/parity.mjs +157 -0
  28. package/examples/angular-templates/run-node.mjs +69 -0
  29. package/examples/angular-templates/vendor/angular/compiler/LICENSE +21 -0
  30. package/examples/desktop-notes/README.md +11 -13
  31. package/examples/dupe-finder/README.md +7 -5
  32. package/examples/fibonacci/README.md +7 -7
  33. package/examples/hello-world/README.md +6 -6
  34. package/examples/json-server/README.md +19 -18
  35. package/examples/mandelbrot-png/README.md +11 -13
  36. package/examples/marked-cli/README.md +38 -37
  37. package/examples/openai-chat/README.md +148 -0
  38. package/examples/openai-chat/bench.mjs +175 -0
  39. package/examples/openai-chat/main.ts +488 -0
  40. package/examples/react-compiler/README.md +170 -0
  41. package/examples/react-compiler/bench.mjs +181 -0
  42. package/examples/react-compiler/main.ts +158 -0
  43. package/examples/react-compiler/parity.mjs +362 -0
  44. package/examples/react-compiler/run-node.mjs +88 -0
  45. package/examples/react-compiler/vendor/babel/LICENSE +22 -0
  46. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-lower.json +15 -0
  47. package/examples/react-compiler/vendor/babel/helper-globals/data/builtin-upper.json +51 -0
  48. package/examples/react-compiler/vendor/charcodes/package.json +25 -0
  49. package/examples/react-compiler/vendor/invariant/LICENSE +21 -0
  50. package/examples/react-compiler/vendor/invariant/invariant.cjs +51 -0
  51. package/examples/react-compiler/vendor/invariant/invariant.d.cts +11 -0
  52. package/examples/react-compiler/vendor/invariant/types/LICENSE +21 -0
  53. package/examples/react-compiler/vendor/jridgewell/gen-mapping/LICENSE +19 -0
  54. package/examples/react-compiler/vendor/jridgewell/resolve-uri/LICENSE +19 -0
  55. package/examples/react-compiler/vendor/jridgewell/sourcemap-codec/LICENSE +19 -0
  56. package/examples/react-compiler/vendor/jridgewell/trace-mapping/LICENSE +19 -0
  57. package/examples/react-compiler/vendor/js-tokens/LICENSE +21 -0
  58. package/examples/react-compiler/vendor/js-tokens/index.cjs +23 -0
  59. package/examples/react-compiler/vendor/js-tokens/index.d.cts +13 -0
  60. package/examples/react-compiler/vendor/jsesc/LICENSE-MIT.txt +20 -0
  61. package/examples/react-compiler/vendor/jsesc/jsesc.cjs +337 -0
  62. package/examples/react-compiler/vendor/jsesc/jsesc.d.cts +384 -0
  63. package/examples/react-compiler/vendor/jsesc/types/LICENSE +21 -0
  64. package/examples/react-compiler/vendor/picocolors/LICENSE +15 -0
  65. package/examples/react-compiler/vendor/picocolors/picocolors.cjs +75 -0
  66. package/examples/react-compiler/vendor/picocolors/picocolors.d.cts +5 -0
  67. package/examples/react-compiler/vendor/picocolors/types.d.ts +51 -0
  68. package/examples/react-compiler/vendor/react-compiler/LICENSE +21 -0
  69. package/examples/react-compiler/vendor/stubs/babel-core.ts +31 -0
  70. package/examples/react-compiler/vendor/stubs/debug.ts +18 -0
  71. package/examples/react-compiler/vendor/stubs/js-tokens.d.ts +13 -0
  72. package/examples/react-compiler/vendor/stubs/pretty-format.ts +18 -0
  73. package/examples/react-compiler/vendor/zod/LICENSE +21 -0
  74. package/examples/react-compiler/vendor/zod-validation-error/LICENSE +9 -0
  75. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/NonEmptyArray.ts +5 -0
  76. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinPath.ts +49 -0
  77. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/joinValues.ts +48 -0
  78. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/stringify.ts +50 -0
  79. package/examples/react-compiler/vendor/zod-validation-error/lib/utils/titleCase.ts +6 -0
  80. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/MessageBuilder.ts +126 -0
  81. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/ValidationError.ts +39 -0
  82. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/custom.ts +12 -0
  83. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/errorMap.ts +78 -0
  84. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/index.ts +2 -0
  85. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidElement.ts +12 -0
  86. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidKey.ts +12 -0
  87. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidStringFormat.ts +131 -0
  88. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidType.ts +54 -0
  89. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidUnion.ts +12 -0
  90. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/invalidValue.ts +40 -0
  91. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/notMultipleOf.ts +12 -0
  92. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooBig.ts +76 -0
  93. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/tooSmall.ts +76 -0
  94. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/types.ts +27 -0
  95. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/errorMap/unrecognizedKeys.ts +27 -0
  96. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromError.ts +13 -0
  97. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodError.ts +61 -0
  98. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/fromZodIssue.ts +38 -0
  99. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/index.ts +20 -0
  100. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationError.ts +5 -0
  101. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isValidationErrorLike.ts +8 -0
  102. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/isZodErrorLike.ts +11 -0
  103. package/examples/react-compiler/vendor/zod-validation-error/lib/v4/toValidationError.ts +20 -0
  104. package/examples/react-compiler/vendor.mjs +688 -0
  105. package/examples/todo-cli/README.md +9 -9
  106. package/examples/yaml-cli/README.md +38 -28
  107. package/package.json +8 -5
  108. package/performance/README.md +195 -0
  109. package/performance/any-dynamic.ts +21 -0
  110. package/performance/any-record-view.ts +20 -0
  111. package/performance/arr-hof.ts +21 -0
  112. package/performance/arr-push-index.ts +15 -0
  113. package/performance/arr-sort.ts +21 -0
  114. package/performance/async-await.ts +24 -0
  115. package/performance/class-dispatch.ts +52 -0
  116. package/performance/events-emit.ts +27 -0
  117. package/performance/exc-throw-rare.ts +25 -0
  118. package/performance/exc-try-catch.ts +26 -0
  119. package/performance/fn-closures.ts +29 -0
  120. package/performance/fn-recursion-tree.ts +31 -0
  121. package/performance/gen-for-of.ts +46 -0
  122. package/performance/json-roundtrip.ts +27 -0
  123. package/performance/map-delete.ts +24 -0
  124. package/performance/map-string-keys.ts +22 -0
  125. package/performance/num-arith-loop.ts +14 -0
  126. package/performance/num-bitwise.ts +21 -0
  127. package/performance/num-mod-int.ts +16 -0
  128. package/performance/num-to-string.ts +16 -0
  129. package/performance/obj-alloc.ts +32 -0
  130. package/performance/regex-exec.ts +29 -0
  131. package/performance/regex-site.ts +28 -0
  132. package/performance/set-ops.ts +20 -0
  133. package/performance/str-char-scan.ts +35 -0
  134. package/performance/str-concat-plus.ts +18 -0
  135. package/performance/str-concat.ts +24 -0
  136. package/performance/str-short-scan.ts +26 -0
  137. package/performance/str-split-join.ts +23 -0
  138. package/performance/str-template.ts +16 -0
  139. package/performance/union-switch.ts +57 -0
  140. package/tsparser/check.go +2 -1
  141. package/tsparser/main.go +1 -0
  142. package/types/typenative-npm.d.ts +3 -2
  143. package/types/typenative.d.ts +42 -12
  144. package/ROUND2-HANDOFF.md +0 -200
@@ -53,17 +53,17 @@ Reproduce with `node bench.mjs [runs=30]`. The script compiles `main.ts`, fills
53
53
  a temp file with 50 items for each runtime, and then times **complete process
54
54
  runs** (spawn to exit) of `todo list` and `todo add`.
55
55
 
56
- **Environment:** Windows 11 Pro, AMD Ryzen 5 5500U, Node v24.19.0, Go 1.26.0,
57
- TypeNative 0.4.1, default (non-`--release`) build.
56
+ **Environment:** Windows 11 Pro, AMD Ryzen 5 7600, Node v26.13.0, Go 1.27.4,
57
+ TypeNative 0.5.0 (unreleased changes), default (non-`--release`) build.
58
58
 
59
59
  | Command | Runtime | min | median | mean | max |
60
60
  |-------------|------------|-----------|-----------|-----------|-----------|
61
- | `todo list` | Node.js | 104.98 ms | 111.37 ms | 112.74 ms | 130.05 ms |
62
- | `todo list` | TypeNative | 14.45 ms | 16.26 ms | 16.44 ms | 20.40 ms |
63
- | `todo add` | Node.js | 105.63 ms | 112.74 ms | 113.33 ms | 133.39 ms |
64
- | `todo add` | TypeNative | 15.23 ms | 16.98 ms | 17.15 ms | 23.72 ms |
61
+ | `todo list` | Node.js | 64.82 ms | 76.07 ms | 75.08 ms | 88.16 ms |
62
+ | `todo list` | TypeNative | 7.94 ms | 9.26 ms | 15.17 ms | 185.65 ms |
63
+ | `todo add` | Node.js | 64.27 ms | 75.78 ms | 75.47 ms | 92.32 ms |
64
+ | `todo add` | TypeNative | 8.76 ms | 10.02 ms | 10.07 ms | 12.51 ms |
65
65
 
66
- **TypeNative answers each command 6.6–6.8x faster** (median). At about 16 ms,
67
- a call feels instant. At about 110 ms, there's a visible pause, and it adds up
66
+ **TypeNative answers each command 7.6–8.2x faster** (median). At about 10 ms,
67
+ a call feels instant. At about 75 ms, there's a noticeable delay, and it adds up
68
68
  when the tool runs from a prompt or a hook on every keystroke or commit. The
69
- binary is a single 3.8 MB file, with no Node install and no `node_modules`.
69
+ binary is a single 4.6 MB file, with no Node install and no `node_modules`.
@@ -82,55 +82,65 @@ and checks that the two JSON outputs are identical:
82
82
  Deployments, Services and ConfigMaps in one stream, from a fixed-seed
83
83
  generator, so every machine gets the same input).
84
84
 
85
- **Environment:** Linux 6.18 container, 4 vCPUs of an Intel Xeon @ 2.80GHz,
86
- Node v24.22.2, Go 1.26.0, TypeNative 0.4.2 (unreleased changes), default
87
- (non-`--release`) build. The binary is 7.3 MB.
85
+ **Environment:** Windows 11 Pro, AMD Ryzen 5 7600 (6 cores, 12 threads),
86
+ Node v26.13.0, Go 1.27.4, TypeNative 0.5.0 (unreleased changes), default
87
+ (non-`--release`) build. The binary is 7.6 MB.
88
88
 
89
89
  (a) `yaml --json < docker-compose.yml`, 30 runs each:
90
90
 
91
91
  | Runtime | min | median | mean | max |
92
92
  | ---------- | --------- | --------- | --------- | --------- |
93
- | Node.js | 214.80 ms | 249.92 ms | 248.16 ms | 305.68 ms |
94
- | TypeNative | 7.63 ms | 9.16 ms | 9.49 ms | 12.83 ms |
93
+ | Node.js | 113.39 ms | 117.24 ms | 120.06 ms | 134.47 ms |
94
+ | TypeNative | 8.71 ms | 9.28 ms | 16.79 ms | 234.75 ms |
95
95
 
96
96
  (b) `yaml --json < manifests.yaml` (10.0 MB), 5 runs each:
97
97
 
98
- | Runtime | min | median | mean | max | MB/s (median) |
99
- | ---------- | --------- | --------- | --------- | --------- | ------------- |
100
- | Node.js | 3,916 ms | 4,226 ms | 4,137 ms | 4,301 ms | 2.37 |
101
- | TypeNative | 14,955 ms | 15,170 ms | 15,184 ms | 15,547 ms | 0.66 |
98
+ | Runtime | min | median | mean | max | MB/s (median) |
99
+ | ---------- | -------- | -------- | -------- | -------- | ------------- |
100
+ | Node.js | 1,316 ms | 1,320 ms | 1,340 ms | 1,375 ms | 7.58 |
101
+ | TypeNative | 5,064 ms | 5,169 ms | 5,270 ms | 5,634 ms | 1.93 |
102
102
 
103
- **Per call, TypeNative is 27x faster** (9 ms vs 250 ms, median). Node's
103
+ **Per call, TypeNative is 13x faster** (9 ms vs 117 ms, median). Node's
104
104
  cost here is mostly startup. It loads and type-strips the 78 TypeScript
105
105
  files on every run before it reads a byte of input. That's what you feel
106
106
  when a tool calls the converter once per file.
107
107
 
108
- **On bulk throughput, TypeNative is 3.6x slower.** Once V8's JIT has warmed
109
- up on a long input, it runs this code faster than the compiled Go does. The
110
- library passes its values around as structural object types and unions
111
- (`Scalar | YAMLMap | YAMLSeq | Pair`, CST tokens), which TypeNative holds as
112
- `interface{}`. Property reads and calls on them go through reflection, and a
113
- value handed to a parameter of a narrower object type is copied field by
114
- field. Garbage collection takes about a fifth of the native run. Both costs
115
- grow linearly with input size, while Node's head start is fixed, so the
116
- native binary finishes first up to about 150–200 KB of YAML per process:
108
+ **On bulk throughput, TypeNative is 3.9x slower.** Once V8's JIT has warmed
109
+ up on a long input, it runs this code faster than the compiled Go does, in
110
+ every phase rather than in one bad spot: lexing, parsing and composing each
111
+ take several times as long as under Node. The library passes its values around as
112
+ structural object types and unions (`Scalar | YAMLMap | YAMLSeq | Pair`, CST
113
+ tokens), which TypeNative holds as `interface{}`, so the cost is spread across
114
+ property reads, conversions between object types and allocation, which alone
115
+ takes about a fifth of the main thread. Garbage collection runs on other cores
116
+ and hardly affects the wall clock. These costs grow linearly with input size,
117
+ while Node's head start is fixed, so the native binary finishes first up to
118
+ about 350 KB of YAML per process:
117
119
 
118
120
  | Input | Node.js | TypeNative |
119
121
  | ------ | ------- | ---------- |
120
- | 16 KB | 284 ms | 38 ms |
121
- | 64 KB | 311 ms | 107 ms |
122
- | 128 KB | 345 ms | 253 ms |
123
- | 1 MB | 862 ms | 1,599 ms |
122
+ | 128 KB | 136 ms | 67 ms |
123
+ | 256 KB | 160 ms | 125 ms |
124
+ | 512 KB | 206 ms | 245 ms |
125
+ | 1 MB | 257 ms | 490 ms |
126
+ | 2 MB | 388 ms | 988 ms |
124
127
 
125
128
  (Medians of 5 full process runs each, same generator.)
126
129
 
127
- Getting here fixed three performance bugs in TypeNative's runtime, all
128
- general:
130
+ Getting here fixed performance bugs in TypeNative's runtime, all general:
129
131
 
130
132
  - Long strings' code-point indexes were evicted by the many short slices a
131
133
  lexer takes, so every sticky-regex match rebuilt the index of the whole
132
- input. That made lexing quadratic: about 23 s for 1 MB before (measured on
133
- a loaded machine), about 1.5 s after.
134
- - Struct field lookups by name are cached per type.
134
+ input. That made lexing quadratic.
135
+ - Properties of objects held as any are read and written through plans cached
136
+ per type and key, with no lock, string hash or reflection on a hit. A read
137
+ that's consumed on the spot, such as a comparison, doesn't box the value.
138
+ - `obj.list.push(x)` on an object held as any appends in place. It used to
139
+ convert the whole array on every push, which made building a list quadratic.
140
+ - Conversions between object types are compiled once per pair of types.
141
+ - `switch` on a value held as any compiles to a string switch when its cases
142
+ are string literals.
143
+ - Regexes run on a VM that works on byte offsets, so a sticky match on a 10 MB
144
+ input costs no more than one on a short string.
135
145
  - `typeof f` types are func types, so the composer's callbacks are called
136
146
  directly instead of through reflection.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typenative",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Build native applications using Typescript.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -19,6 +19,7 @@
19
19
  "conformance": "node scripts/conformance.mjs",
20
20
  "conformance:parallel": "node scripts/conformance-parallel.mjs",
21
21
  "bootstrap:check": "node scripts/bootstrap-check.mjs",
22
+ "perf": "node scripts/performance.mjs",
22
23
  "test": "npm run conformance",
23
24
  "release": "npm publish"
24
25
  },
@@ -32,13 +33,15 @@
32
33
  "url": "https://github.com/danisss9/typenative/issues"
33
34
  },
34
35
  "homepage": "https://github.com/danisss9/typenative#readme",
36
+ "engines": {
37
+ "node": ">=26"
38
+ },
35
39
  "devDependencies": {
36
- "@types/inquirer": "^9.0.10",
37
- "@types/node": "^24.19.2",
38
- "rimraf": "^6.1.3"
40
+ "@types/node": "^26.6.6",
41
+ "rimraf": "^6.1.4"
39
42
  },
40
43
  "dependencies": {
41
- "inquirer": "^14.2.3",
44
+ "inquirer": "^14.2.5",
42
45
  "typescript": "^6.0.3"
43
46
  }
44
47
  }
@@ -0,0 +1,195 @@
1
+ # Performance probes
2
+
3
+ Micro-benchmarks for TypeNative's hot paths. [conformance/](../conformance/)
4
+ proves that a construct compiles correctly, and this folder measures how fast the
5
+ compiled code runs. Each probe is one small standalone TypeScript program that
6
+ exercises one construct (string `+=`, `Map` lookups, `switch` over a
7
+ discriminated union, `any` property access, …) and runs unchanged under Node.js
8
+ and as a TypeNative binary. A transpiler or runtime change can then be measured
9
+ on the exact path it touches, instead of only through whole programs like
10
+ [examples/marked-cli](../examples/marked-cli/) where no single hot spot stands
11
+ out.
12
+
13
+ ## Running
14
+
15
+ From a checkout, after `npm run build`:
16
+
17
+ ```sh
18
+ npm run perf # every probe, 7 interleaved runs each
19
+ node scripts/performance.mjs str # only probes whose name contains "str"
20
+ node scripts/performance.mjs map --runs 15 # more runs for a tighter median
21
+ node scripts/performance.mjs --write # also update the results table below
22
+ node scripts/performance.mjs --native # compile with the self-hosted binary
23
+ ```
24
+
25
+ The runner ([scripts/performance.mjs](../scripts/performance.mjs)) builds each
26
+ probe once with the TypeNative CLI. It then runs the probe under Node.js and as
27
+ the native binary, alternating which runtime goes first in each round. It
28
+ prints a markdown table of the in-program timings. A probe stops taking more
29
+ rounds once its native runs have used 15 s, so a pathological probe can't stall
30
+ the suite. Those rows show how many runs they got.
31
+
32
+ The runner fails (exit 1) only when a probe doesn't build, crashes, or prints a
33
+ different `checksum` under the two runtimes. A slow probe never fails it,
34
+ because slowness is the thing being measured.
35
+
36
+ `--write` replaces the rows of the probes that ran inside the results region
37
+ below, keeps the other rows, and refreshes the environment line. Run the full
38
+ suite on an idle machine before committing new numbers.
39
+
40
+ ## Writing a probe
41
+
42
+ A probe is `performance/<area>-<name>.ts`. Areas: `num`, `str`, `arr`, `map`,
43
+ `set`, `obj`, `class`, `union`, `any`, `fn`, `gen`, `regex`, `json`, `exc`,
44
+ `events`, `async`.
45
+
46
+ ```ts
47
+ // perf: one line saying what this measures (shown in the results table)
48
+ import { performance } from 'node:perf_hooks';
49
+
50
+ const input = /* build the input here, outside the timed region */;
51
+
52
+ const start = performance.now();
53
+ let total = 0;
54
+ /* the hot loop, folding its results into total */
55
+ const elapsed = performance.now() - start;
56
+
57
+ console.log(`checksum: ${total}`);
58
+ console.log(`elapsed: ${elapsed.toFixed(2)} ms`);
59
+ ```
60
+
61
+ - **Line 1** must be `// perf: <description>`. The table's "Measures" column
62
+ is read from it.
63
+ - **Time only the hot loop.** Process startup is excluded on purpose, because
64
+ [examples/hello-world](../examples/hello-world/) already measures that.
65
+ - **Derive the checksum from the work**, so neither compiler can drop the loop.
66
+ The runner compares the checksums, which also catches wrong results.
67
+ - **Size it for Node.js at roughly 100–500 ms.** Shorter runs are noisy. If
68
+ TypeNative takes many seconds on it, that is a finding: shrink the probe only
69
+ until a run takes a few seconds, and note it below.
70
+ - **Measure one thing.** Keep `%` out of hot loops: it compiles to Go's slow
71
+ `math.Mod` (see [findings](#findings)) and would swamp whatever the probe is
72
+ about. Use `i & 1023` and friends instead.
73
+ - Keep it standalone (no local imports), like the conformance probes.
74
+
75
+ ## Methodology and caveats
76
+
77
+ - Numbers are the program's own `performance.now()` timings, never spawn-to-exit
78
+ times. Speedups compare medians, and the minimums are listed too because they
79
+ are the most stable figure on a noisy machine.
80
+ - Background load skews results a lot. A self-hosted compile or a .NET build
81
+ running in the background cut both runtimes about 3x on the reference
82
+ machine. Interleaving the runtimes spreads drift across both, but it can't
83
+ remove load, so check that the machine is idle before trusting a run.
84
+ - Micro-benchmarks flatter JITs: V8 optimizes these tight loops with type
85
+ feedback that a large program rarely gets. Use the ratios here to rank hot
86
+ paths against each other and to track them over time. They are not a
87
+ prediction for whole programs; see [examples/](../examples/) for those.
88
+ - To find out *why* a probe (or any program) is slow, build it with `--profile`:
89
+ the binary writes a CPU profile to `$TYPENATIVE_CPUPROFILE` (default
90
+ `cpu.pprof`) when it exits. Read it with `go tool pprof -top -cum <exe> <profile>`.
91
+ For example, `node bin/cli.js --source performance/num-bitwise.ts --output bw.exe --profile`.
92
+ `--emit-go <dir>` shows the Go the profile's lines refer to.
93
+
94
+ ## Results
95
+
96
+ <!-- perf-results:start -->
97
+
98
+ Last run 2026-11-13 (only `gen-for-of` probes updated): Windows_NT 10.0.26300, AMD Ryzen 5 7600 6-Core Processor, Node v26.13.0, go1.27.4 windows/amd64, TypeNative 0.5.0, 15 interleaved runs per probe.
99
+
100
+ | Probe | Measures | Node ms (min / median) | TypeNative ms (min / median) | TypeNative vs Node (median) |
101
+ | ----- | -------- | ---------------------: | ---------------------------: | :-------------------------- |
102
+ | [any-dynamic](any-dynamic.ts) | property reads and writes on `any` objects (nested objects, arrays) | 51.8 / 53.3 | 2474 / 2501 (6 runs) | 46.9x slower |
103
+ | [any-record-view](any-record-view.ts) | viewing an `any` object as `Record<string, any>` and reading keys through it | 5.6 / 6.1 | 269 / 273 | 45.0x slower |
104
+ | [arr-hof](arr-hof.ts) | `map` / `filter` / `reduce` / `some` chains with closure callbacks | 89.8 / 91.6 | 26.9 / 27.7 | **3.3x faster** |
105
+ | [arr-push-index](arr-push-index.ts) | `push`, indexed reads/writes and `length` on number arrays | 52.5 / 54.3 | 55.0 / 55.7 | 1.0x slower |
106
+ | [arr-sort](arr-sort.ts) | `sort` of numbers with a comparator and of strings in default order | 125 / 127 | 347 / 354 | 2.8x slower |
107
+ | [async-await](async-await.ts) | `await` chains of async functions that resolve immediately | 99.5 / 104 | 201 / 206 | 2.0x slower |
108
+ | [class-dispatch](class-dispatch.ts) | virtual method calls through an abstract base class and an interface | 68.6 / 71.7 | 124 / 127 | 1.8x slower |
109
+ | [events-emit](events-emit.ts) | `EventEmitter` `emit` to listeners taking 0, 1 and 2 arguments | 73.6 / 73.9 | 655 / 658 | 8.9x slower |
110
+ | [exc-throw-rare](exc-throw-rare.ts) | `try`/`catch`/`finally` in a hot loop where nothing throws | 204 / 205 | 241 / 242 | 1.2x slower |
111
+ | [exc-try-catch](exc-try-catch.ts) | `try`/`catch`/`finally` in a hot loop where one call in 1,024 throws | 24.7 / 24.9 | 60.8 / 61.1 | 2.5x slower |
112
+ | [fn-closures](fn-closures.ts) | creating closures over mutable state and calling them indirectly | 144 / 145 | 58.6 / 60.0 | **2.4x faster** |
113
+ | [fn-recursion-tree](fn-recursion-tree.ts) | building and walking binary trees (recursion plus allocation) | 101 / 103 | 149 / 152 | 1.5x slower |
114
+ | [gen-for-of](gen-for-of.ts) | sync generators (a method, `*[Symbol.iterator]()`, `yield*`) consumed by `for…of` | 52.5 / 53.6 | 11.6 / 12.2 | **4.4x faster** |
115
+ | [json-roundtrip](json-roundtrip.ts) | `JSON.stringify` and `JSON.parse` of an array of nested objects | 38.5 / 39.9 | 96.9 / 99.5 | 2.5x slower |
116
+ | [map-delete](map-delete.ts) | `Map<string, number>` insert/delete churn (an LRU-style sliding window) | 29.3 / 36.0 | 165 / 167 | 4.6x slower |
117
+ | [map-string-keys](map-string-keys.ts) | `Map<string, number>` `set` / `get` / `has` word counting | 92.3 / 93.5 | 118 / 119 | 1.3x slower |
118
+ | [num-arith-loop](num-arith-loop.ts) | tight float64 loop with `%`, `*` and `Math.floor` | 76.5 / 77.4 | 159 / 162 | 2.1x slower |
119
+ | [num-bitwise](num-bitwise.ts) | bitwise and, or, xor and shifts (`<<`, `>>`, `>>>`) on integers, and flag tests | 21.6 / 22.3 | 114 / 116 | 5.2x slower |
120
+ | [num-mod-int](num-mod-int.ts) | `%` on integer operands (hash buckets, cycling indexes) | 62.5 / 63.8 | 187 / 191 | 3.0x slower |
121
+ | [num-to-string](num-to-string.ts) | number/string conversion: `String(n)`, `toFixed`, `Number(str)`, `parseInt` | 102 / 105 | 402 / 416 | 4.0x slower |
122
+ | [obj-alloc](obj-alloc.ts) | allocating many short-lived object literals and class instances | 62.5 / 63.4 | 187 / 191 | 3.0x slower |
123
+ | [regex-exec](regex-exec.ts) | regex `test`, `exec` with groups and global `replace` over log lines | 67.9 / 69.5 | 105 / 107 | 1.5x slower |
124
+ | [regex-site](regex-site.ts) | `/g` regex literals evaluated inside a hot function, and `.index` on long input | 78.2 / 83.8 | 159 / 168 | 2.0x slower |
125
+ | [set-ops](set-ops.ts) | `Set<number>` `add` / `has` / `delete` on a 16,384-entry set | 38.6 / 39.5 | 95.5 / 97.0 | 2.5x slower |
126
+ | [str-char-scan](str-char-scan.ts) | lexer-style scan of a large string with `charCodeAt` and `str[i]` | 79.8 / 81.0 | 326 / 327 | 4.0x slower |
127
+ | [str-concat](str-concat.ts) | growing ~20 KB strings with `s += x` and `s = s + …` (each pass starts empty) | 10.1 / 10.6 | 25.5 / 26.4 | 2.5x slower |
128
+ | [str-concat-plus](str-concat-plus.ts) | growing strings with `s = s + x` (not `+=`), each pass starting empty | 30.5 / 31.8 | 97.1 / 101 | 3.2x slower |
129
+ | [str-short-scan](str-short-scan.ts) | `charCodeAt(i)` / `s[i]` scans of many short (< 512 byte) lines | 30.8 / 31.1 | 195 / 196 | 6.3x slower |
130
+ | [str-split-join](str-split-join.ts) | `split`, `join`, `indexOf`, `slice` and `trim` on CSV-like lines | 56.0 / 57.2 | 40.5 / 40.8 | **1.4x faster** |
131
+ | [str-template](str-template.ts) | template literals mixing strings, integers, floats and booleans | 53.5 / 54.7 | 84.1 / 84.6 | 1.5x slower |
132
+ | [union-switch](union-switch.ts) | evaluating an expression tree of a discriminated union with `switch (e.kind)` | 120 / 125 | 488 / 495 | 4.0x slower |
133
+
134
+ <!-- perf-results:end -->
135
+
136
+ ## Findings
137
+
138
+ Causes behind the worst rows. Each one is checked against the generated Go
139
+ (`--emit-go`), a `--profile` CPU profile, or the runtime source in
140
+ [src/transpiler.ts](../src/transpiler.ts). Update this section when a fix
141
+ lands or a new cause is confirmed. Before/after figures are native medians on
142
+ the reference machine.
143
+
144
+ ### Fixed
145
+
146
+ | Probe | Cause | Fix | Before → after |
147
+ | ----- | ----- | --- | -------------- |
148
+ | `num-bitwise` (and every probe that uses `&`) | Every bitwise operand went through `TnInt32`, which called `math.Mod(f, 2^32)`: about 90% of the probe's time. | `TnInt32` converts in-range values directly and falls back to `math.Mod` only past ±2^63. Literal operands fold at compile time, and nested bitwise expressions stay `int32` between operators. | 2160 → 129 ms |
149
+ | `num-arith-loop`, `num-mod-int` | `a % b` compiled to `math.Mod`, whose cost grows with the exponent gap between the operands (about 150 ns for `2e8 % 13`). | `TnMod`: an `int64` remainder when both operands are integers that fit, keeping a `-0` result; `math.Mod` otherwise. | 4527 → 162 ms; 2827 → 188 ms |
150
+ | `gen-for-of` | A generator ran as a goroutine sending on a channel, in lockstep with the loop: two goroutine hand-offs and two `sync.Map` lookups per value. | A sync generator also compiles to a push form, `name__seq(args)`: a Go range function whose `yield` runs the loop body. `for…of` over a direct generator call (or a class's `*[Symbol.iterator]()`) uses it. A break unwinds the generator through its `finally` blocks, and a throw from the loop body passes its `catch` clauses, as in JS. `.next()`, spread and stored generators keep the channel form. | 1843 → 12 ms |
151
+ | `set-ops`, `map-delete` | `TnMap.Delete` scanned and spliced the insertion-order key slice, so each delete was O(size). Every `Get`/`Has`/`Set` also called `reflect.TypeFor[K]().Kind()`. | Deletes mark the key's slot dead in O(1) (an index map built on the first delete of a map past 16 keys) and dead slots are compacted before keys are read. The key-kind check is made once per map. | 1556 → 97 ms; 367 → 167 ms |
152
+ | `any-record-view` | Viewing an `any` object as `Record<string, any>` rebuilt it through reflection on every conversion. | `TnRecordOf` wraps the object's own map in a `TnMap` (writes through the record reach the object, as in JS). | 1696 → 273 ms |
153
+ | `str-concat`, `str-concat-plus` | `s = s + a + b` compiled to Go string concatenation, which copies all of `s`: O(n²) for a growing string. `TnStrAppend` also locked with `defer`. | `s = s + …` on a string variable or field (the target as the leftmost operand) compiles to `TnStrAppend`, like `s += …`, and the lock no longer uses `defer`. | 51.5 → 26.4 ms; 3365 → 101 ms |
154
+ | `str-short-scan` | For strings under 512 bytes, `charCodeAt(i)` rescanned `s[:i+1]` for ASCII and `s.length` rescanned all of `s`, so walking a line was O(n²). | The ASCII answer for the last short string asked about is remembered (the entry holds the string). Indexes under 64 still scan their few bytes. | 300 → 196 ms |
155
+ | `any-dynamic` | Reads of `any` objects missed the field-plan table and went through accessor and reflect checks before reaching the map. Writes boxed every value through `reflect.ValueOf`. | `TnGetRef`/`TnGetPeek` read a `map[string]interface{}` first. `tnBoxArray` returns scalars and maps without reflect. | 3812 → 2501 ms |
156
+ | `num-to-string` | `toFixed` formatted 1100 digits on every call to round exactly. | `strconv` already rounds to nearest. Only a value exactly on a tie (its last binary fraction digit at 2^-(d+1)) takes the exact path. | 667 → 416 ms |
157
+ | `events-emit` | `TnInvoke` called every listener through `reflect.Value.Call`. `emit` copied the listener list and built a `kept` list on every call. | Typed fast paths for `func()`, `func(any)`, `func(any, any)`, `func(...any)`, `func(float64)` and `func(string)`. `emit` uses the copy-on-write listener slice as its snapshot. | 1372 → 658 ms |
158
+ | `regex-site` | Each evaluation of a regex literal looked its compiled program up again (key concatenation and a mutex). | One package-level `TnRegexSite` per literal shares the program and RE2 fallbacks. Each evaluation is still a new `RegExp` with its own `lastIndex`. | 177 → 168 ms |
159
+ | `gen-for-of` (examples) | Generators called through dynamic dispatch (`unit.ops()` on an abstract `CompilationUnit`, 26 phases of angular-templates) still ran as goroutines, and `for…of` over them collected every value first; spread and `Array.from` of a generator received through reflect. | `TnCallSeq_<m>[T]` dispatches a generator method on a dynamic receiver to the class's push form (its channel in lockstep for a generator without one, any other value's elements otherwise), for `for…of`, `yield*` and `super.m()`. A spread or `Array.from` of a generator call collects its push form into a typed slice (`TnGeneratorItems`). | angular-templates at 64 KB: 721 → 601 ms |
160
+ | `class-dispatch` | A call on an abstract base class or an interface went through `TnCall_<m>(recv, args ...interface{})`: arguments and the result boxed, then unboxed with `TnAs`. | When every class of the receiver's declared hierarchy declares the method with the same Go signature, the call goes through `TnCall_<C>_<m>(recv, a P0, …) R`: a type switch calling the method with its own types, the boxed dispatcher only for any other receiver. The call's inferred type is `R`, so the value isn't boxed again where it's used. | 709 → 124 ms |
161
+ | `async-await` | Each async call started a goroutine and handed the JS baton over twice, and each settle allocated two wake-up channels even with nobody waiting. | An async function that awaits only calls of other such functions (whose promises are settled when they return), with no `for await` and no promise returned, runs on the caller's goroutine (`TnRunAsyncInline`). `TnAsyncSend` / `TnAsyncClose` allocate a wake-up channel only for a parked awaiter. | 1985 → 201 ms |
162
+ | `json-roundtrip` | `JSON.parse` built a `TnMap` per object from `encoding/json` tokens, then `as Item[]` converted every map to a struct through `TnConvertDynamic`. | `JSON.parse(text)` into a typed slot is `TnJSONParseTyped[T]`: a scanner decodes the text straight into `T` (per-type plans over field offsets) when every object has `T`'s keys in its field order and every value its kind; anything else (other keys, null, any fields, invalid text) decodes and converts as before. | 347 → 97 ms |
163
+ | `num-bitwise` | Loop counters and flag locals were `float64`, so every bitwise operand converted float64 to int32 through `TnInt32`. | A `for` loop's `let` counter (an integer literal start, `++` / `--`, never written in the body) is a Go `int`, and a block `const` holding a bitwise result an `int32`, when every read is an arithmetic, comparison, bitwise, index or template operand: reads are `float64(i)`, bitwise operands take the integer directly. | 128 → 114 ms |
164
+
165
+ ### Open
166
+
167
+ | Probe | Cause | Status |
168
+ | ----- | ----- | ------ |
169
+ | `any-dynamic` | What remains is the representation: an `any` object is a Go `map[string]interface{}`, so every property access hashes its key (`memHashAES` and map lookups are about 45%), where V8 reads a slot through a hidden class. | open |
170
+ | `events-emit` | Listener shapes other than the fast paths (here `(a: number, b: string)`) still go through `reflect.Value.Call` (about a third), and each `emit` hashes the event name. | open |
171
+ | `str-short-scan`, `str-char-scan` | Indexes under 64 still rescan their prefix for ASCII (`tnStrIsASCII` is 40% of `str-short-scan`). A loop over `s.charCodeAt(i)` could test `s` once before the loop. | open |
172
+ | `num-mod-int`, `num-bitwise` | Integer loop counters are Go `int`s now, but `%` still runs on `float64` (`TnMod` converts both operands and checks them, then divides with `idiv`), and other integral locals (`k = (k + i) % 97`, module constants such as `F_A = 1 << 0`) stay `float64`. A `TnMod` by a constant divisor would let Go multiply instead of divide, but any fallback call puts the helper over Go's inlining budget; it would have to be emitted inline. | open |
173
+
174
+ Bugs found while writing the probes (not performance, not fixed here):
175
+ `'x' + null` and `'x' + undefined` render `<nil>`, and a `-0` concatenated
176
+ into a string renders `-0e+0` (JS gives `null`, `undefined` and `0`); a
177
+ subclass of a class with `*[Symbol.iterator]()` can't be iterated (the
178
+ generator isn't copied into it); and examples/marked-cli's parity run fails
179
+ 69 `--tokens` cases at this commit and before (a `def` token's unmatched
180
+ `title` group prints `""` where Node omits `undefined`).
181
+
182
+ Found while pinning the fixes above (also before them, not fixed here): an
183
+ `await` of a promise that is already settled resumes on the spot, so in
184
+ `const p = f(); log('x')` the part of `f` after its first `await` runs
185
+ before `x` (JS runs it after); a `for…of` over an array doesn't see elements
186
+ pushed during the loop; a class method returning `null` (`next(): Base |
187
+ null`) and a typed field read from JSON `null` compare `=== null` as
188
+ `undefined`, and `await` of a `Promise<void>` gives `{}`; an object literal
189
+ typed as an interface, called through a dynamic receiver, throws `area is
190
+ not a function`; a class whose arrow-function field implements an interface
191
+ method, and `[...shapes]` of a `Base[]` into a `Shape[]`, don't compile;
192
+ `.length` counts a character outside the BMP once (JS counts two UTF-16
193
+ units); `JSON.parse` of a number past the float range (`1e400`) throws
194
+ where JS gives `Infinity`; and a JSON object whose keys come in another
195
+ order than its type's fields loses that order once converted to the type.
@@ -0,0 +1,21 @@
1
+ // perf: property reads and writes on `any` objects (nested objects, arrays)
2
+ import { performance } from 'node:perf_hooks';
3
+
4
+ const records: any[] = [];
5
+ for (let i = 0; i < 10_000; i++) {
6
+ records.push({ id: i, name: 'item' + i, price: i % 100, tags: ['a', 'b'], meta: { score: i % 7 } });
7
+ }
8
+
9
+ const start = performance.now();
10
+ let total = 0;
11
+ for (let pass = 0; pass < 2500; pass++) {
12
+ for (const r of records) {
13
+ total += r.price + r.meta.score + r.tags.length;
14
+ r.price = r.price < 99 ? r.price + 1 : 0;
15
+ if (r.name.length > 6) total++;
16
+ }
17
+ }
18
+ const elapsed = performance.now() - start;
19
+
20
+ console.log(`checksum: ${total}`);
21
+ console.log(`elapsed: ${elapsed.toFixed(2)} ms`);
@@ -0,0 +1,20 @@
1
+ // perf: viewing an `any` object as `Record<string, any>` and reading keys through it
2
+ import { performance } from 'node:perf_hooks';
3
+
4
+ const records: any[] = [];
5
+ for (let i = 0; i < 10_000; i++) {
6
+ records.push({ id: i, name: 'item' + i, price: i % 100, tags: ['a', 'b'] });
7
+ }
8
+
9
+ const start = performance.now();
10
+ let total = 0;
11
+ for (let pass = 0; pass < 200; pass++) {
12
+ for (const r of records) {
13
+ const bag: Record<string, any> = r;
14
+ total += bag['price'] + bag['name'].length;
15
+ }
16
+ }
17
+ const elapsed = performance.now() - start;
18
+
19
+ console.log(`checksum: ${total}`);
20
+ console.log(`elapsed: ${elapsed.toFixed(2)} ms`);
@@ -0,0 +1,21 @@
1
+ // perf: `map` / `filter` / `reduce` / `some` chains with closure callbacks
2
+ import { performance } from 'node:perf_hooks';
3
+
4
+ const data: number[] = [];
5
+ for (let i = 0; i < 100_000; i++) data.push((i * 7919) % 10007);
6
+
7
+ const start = performance.now();
8
+ let total = 0;
9
+ for (let pass = 0; pass < 50; pass++) {
10
+ const limit = 5000 + pass;
11
+ const result = data
12
+ .map((x) => x * 2)
13
+ .filter((x) => x > limit)
14
+ .reduce((acc, x) => acc + (x & 127), 0);
15
+ total += result;
16
+ if (data.some((x) => x === limit)) total++;
17
+ }
18
+ const elapsed = performance.now() - start;
19
+
20
+ console.log(`checksum: ${total}`);
21
+ console.log(`elapsed: ${elapsed.toFixed(2)} ms`);
@@ -0,0 +1,15 @@
1
+ // perf: `push`, indexed reads/writes and `length` on number arrays
2
+ import { performance } from 'node:perf_hooks';
3
+
4
+ const n = 5_000_000;
5
+
6
+ const start = performance.now();
7
+ const a: number[] = [];
8
+ for (let i = 0; i < n; i++) a.push(i & 1023);
9
+ for (let i = 1; i < a.length; i++) a[i] = (a[i] + a[i - 1]) & 4095;
10
+ let sum = 0;
11
+ for (let i = 0; i < a.length; i += 3) sum += a[i];
12
+ const elapsed = performance.now() - start;
13
+
14
+ console.log(`checksum: ${sum}`);
15
+ console.log(`elapsed: ${elapsed.toFixed(2)} ms`);
@@ -0,0 +1,21 @@
1
+ // perf: `sort` of numbers with a comparator and of strings in default order
2
+ import { performance } from 'node:perf_hooks';
3
+
4
+ const nums: number[] = [];
5
+ const strs: string[] = [];
6
+ let seed = 12345;
7
+ for (let i = 0; i < 300_000; i++) {
8
+ seed = (seed * 1103515245 + 12345) % 2147483648;
9
+ nums.push(seed % 1000000);
10
+ strs.push('k' + (seed % 100000));
11
+ }
12
+
13
+ const start = performance.now();
14
+ const a = nums.slice();
15
+ a.sort((x, y) => x - y);
16
+ const b = strs.slice();
17
+ b.sort();
18
+ const elapsed = performance.now() - start;
19
+
20
+ console.log(`checksum: ${a[0] + a[a.length >> 1] + a[a.length - 1]} ${b[0]} ${b[b.length >> 1]} ${b[b.length - 1]}`);
21
+ console.log(`elapsed: ${elapsed.toFixed(2)} ms`);
@@ -0,0 +1,24 @@
1
+ // perf: `await` chains of async functions that resolve immediately
2
+ import { performance } from 'node:perf_hooks';
3
+
4
+ async function leaf(n: number): Promise<number> {
5
+ return n & 15;
6
+ }
7
+
8
+ async function middle(n: number): Promise<number> {
9
+ const a = await leaf(n);
10
+ const b = await leaf(n + 1);
11
+ return a + b;
12
+ }
13
+
14
+ async function main(): Promise<void> {
15
+ const n = 1_000_000;
16
+ const start = performance.now();
17
+ let total = 0;
18
+ for (let i = 0; i < n; i++) total += await middle(i);
19
+ const elapsed = performance.now() - start;
20
+ console.log(`checksum: ${total}`);
21
+ console.log(`elapsed: ${elapsed.toFixed(2)} ms`);
22
+ }
23
+
24
+ main();
@@ -0,0 +1,52 @@
1
+ // perf: virtual method calls through an abstract base class and an interface
2
+ import { performance } from 'node:perf_hooks';
3
+
4
+ interface Shape {
5
+ area(): number;
6
+ }
7
+
8
+ abstract class Base implements Shape {
9
+ abstract area(): number;
10
+ scaled(k: number): number {
11
+ return this.area() * k;
12
+ }
13
+ }
14
+
15
+ class Square extends Base {
16
+ side: number;
17
+ constructor(side: number) {
18
+ super();
19
+ this.side = side;
20
+ }
21
+ area(): number {
22
+ return this.side * this.side;
23
+ }
24
+ }
25
+
26
+ class Rect extends Base {
27
+ w: number;
28
+ h: number;
29
+ constructor(w: number, h: number) {
30
+ super();
31
+ this.w = w;
32
+ this.h = h;
33
+ }
34
+ area(): number {
35
+ return this.w * this.h;
36
+ }
37
+ }
38
+
39
+ const shapes: Base[] = [];
40
+ for (let i = 0; i < 1000; i++) shapes.push(i % 2 === 0 ? new Square(i % 10) : new Rect(i % 7, 3));
41
+ const asIface: Shape[] = shapes;
42
+
43
+ const start = performance.now();
44
+ let total = 0;
45
+ for (let pass = 0; pass < 25000; pass++) {
46
+ for (let i = 0; i < shapes.length; i++) total += shapes[i].scaled(2);
47
+ for (const s of asIface) total += s.area();
48
+ }
49
+ const elapsed = performance.now() - start;
50
+
51
+ console.log(`checksum: ${total}`);
52
+ console.log(`elapsed: ${elapsed.toFixed(2)} ms`);
@@ -0,0 +1,27 @@
1
+ // perf: `EventEmitter` `emit` to listeners taking 0, 1 and 2 arguments
2
+ import { EventEmitter } from 'node:events';
3
+ import { performance } from 'node:perf_hooks';
4
+
5
+ const bus = new EventEmitter();
6
+ let total = 0;
7
+ bus.on('tick', () => {
8
+ total++;
9
+ });
10
+ bus.on('data', (n: number) => {
11
+ total += n & 7;
12
+ });
13
+ bus.on('pair', (a: number, b: string) => {
14
+ total += a + b.length;
15
+ });
16
+
17
+ const n = 3_000_000;
18
+ const start = performance.now();
19
+ for (let i = 0; i < n; i++) {
20
+ bus.emit('tick');
21
+ bus.emit('data', i);
22
+ bus.emit('pair', i & 3, 'ab');
23
+ }
24
+ const elapsed = performance.now() - start;
25
+
26
+ console.log(`checksum: ${total}`);
27
+ console.log(`elapsed: ${elapsed.toFixed(2)} ms`);
@@ -0,0 +1,25 @@
1
+ // perf: `try`/`catch`/`finally` in a hot loop where nothing throws
2
+ import { performance } from 'node:perf_hooks';
3
+
4
+ function step(i: number): number {
5
+ if (i < 0) throw new Error('negative');
6
+ return i & 255;
7
+ }
8
+
9
+ const n = 50_000_000;
10
+ const start = performance.now();
11
+ let total = 0;
12
+ let cleanups = 0;
13
+ for (let i = 0; i < n; i++) {
14
+ try {
15
+ total += step(i);
16
+ } catch (e) {
17
+ total -= 1;
18
+ } finally {
19
+ cleanups++;
20
+ }
21
+ }
22
+ const elapsed = performance.now() - start;
23
+
24
+ console.log(`checksum: ${total + cleanups}`);
25
+ console.log(`elapsed: ${elapsed.toFixed(2)} ms`);
@@ -0,0 +1,26 @@
1
+ // perf: `try`/`catch`/`finally` in a hot loop where one call in 1,024 throws
2
+ import { performance } from 'node:perf_hooks';
3
+
4
+ function risky(i: number): number {
5
+ if ((i & 1023) === 0) throw new Error('bad ' + i);
6
+ return i & 7;
7
+ }
8
+
9
+ const n = 10_000_000;
10
+
11
+ const start = performance.now();
12
+ let total = 0;
13
+ let caught = 0;
14
+ for (let i = 0; i < n; i++) {
15
+ try {
16
+ total += risky(i);
17
+ } catch (e) {
18
+ caught++;
19
+ } finally {
20
+ total++;
21
+ }
22
+ }
23
+ const elapsed = performance.now() - start;
24
+
25
+ console.log(`checksum: ${total + caught}`);
26
+ console.log(`elapsed: ${elapsed.toFixed(2)} ms`);