Skip to content

perf(runtime): keep TypeScript-extended instances out of prototype mode - #2148

Merged
edusperoni merged 1 commit into
mainfrom
perf/extended-construct-no-prototype
Nov 23, 2026
Merged

edusperoni merged 1 commit into
mainfrom
perf/extended-construct-no-prototype

Conversation

@edusperoni

@edusperoni edusperoni commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Creating an instance of a TypeScript class that extends a Java class (class X extends android.view.View, compiled to ES5 with __extends) costs several times more than the same class made with .extend(). Most of that comes from how internal/ts_helpers.js builds the instance.

Root cause. For native base classes, __extends replaces _super.call/_super.apply. The replacement created the Java-backed instance, then set it as the prototype of the constructor's own this (thiz.__proto__ = native). In V8, setting an object as a prototype switches it to prototype mode and gives it a map of its own. So every instance ended up with a unique map:

  • each field the constructor stores (_this.a = ...) misses its inline cache and copies the map, about 1.4 µs per field;
  • the switch itself adds about 7 µs of fixed overhead per instance.

This happens in every wrapper-lifetime mode, and later property access on the instance pays for the unshared map too.

Change. The helper now builds the instance with Reflect.construct and never makes it a prototype. It stores the instance under a private symbol on the constructor's this, and __native looks for it there. TypeScript 2+ output (var _this = _super.call(this, ...) || this; ...; return _this;) uses the instance super() returns directly, so it behaves as before. Reflect.construct also replaces the Function.prototype.bind.apply construction.

Not supported any more: pre-TypeScript 2 constructor shapes

TypeScript 1.x emitted _super.call(this) without using its result, and kept working on its own this. That this used to reach the Java instance through its prototype; it no longer does.

  • A constructor that ends with return __native(this) still works: __native moves the fields set on this to the instance and returns the instance. The existing specs in testsForTypescript.js that use this shape still pass.
  • Between _super.call(this) and __native(this), calling Java methods on this or passing this to Java no longer works.
  • A constructor that returns neither __native(this) nor the instance gets back a plain JS object, not the Java instance.

Measurements

Samsung SM-G780G (Android 13). Optimized release APKs (-Poptimized -Prelease -Pabis=arm64-v8a), built with a local benchmark harness (not part of this PR).

First run: construction (6 rounds), µs per instance, for 1/3/5 fields set in the constructor. The floor is the same class built with .extend() and the same fields.

row mode BASE STASH .extend() floor
construct resurrecting 13.9 / 17.5 / 19.5 4.1 / 5.1 / 4.9 3.7 / 3.7 / 3.7
construct + JS call + Java→JS resurrecting 21.3 / 24.0 / 26.5 8.2 / 9.4 / 9.2
construct canary/all 18.5 / 22.3 / 25.4 7.0 / 10.2 / 12.3 6.7 / 8.0 / 10.0
construct + JS call + Java→JS canary/all 25.5 / 30.6 / 33.9 12.4 / 16.0 / 18.0

A/A (BASEb vs BASE) on these rows stayed within ±6%, except resurrecting construct with 5 fields at +12%. On every TS row the STASH range does not overlap the pooled BASE + BASEb range. The .extend() rows, which this change does not touch, moved by less than 1.5%.

Second run (4 rounds resurrecting, 5 rounds canary/all), taken later with the same APK pairs. From one round to the next, absolute numbers moved by up to 1.7× for every label, the unchanged rows included, so this run is reported as STASH/BASE ratios within a round: median [min–max] over rounds. A/A is BASEb/BASE in the same rounds. In canary/all round 1, three STASH launches were lost to another process on the device; a fifth round makes up for them.

Construction reproduces the first run. STASH/BASE for 1/3/5 fields; canary/all with [min–max] over its 5 rounds:

row resurrecting canary/all
construct, TS class extending a test Java class 0.29 / 0.29 / 0.25 0.39 [0.37–0.64] / 0.47 [0.46–0.76] / 0.49 [0.48–0.77]
construct, TS class extending java.lang.Object 0.30 / 0.27 / 0.22 0.42 [0.37–0.44] / 0.43 [0.41–0.49] / 0.46 [0.43–0.53]
construct + JS call + Java→JS 0.43 / 0.39 / 0.33 0.59 [0.47–0.82] / 0.59 [0.50–0.88] / 0.57 [0.55–0.85]
A/A, first row 0.96 / 0.98 / 0.96 1.02 [0.96–1.84] / 1.05 [0.99–1.78] / 0.98 [0.95–1.72]
.extend() construct (control) 1.01 / 1.00 / 0.99 0.99 / 0.97 / 0.95

In canary/all the test-class rows are bimodal from launch to launch, for every label: 1-field construction ran at about 17 or 29 µs with BASE and about 7 or 11 µs with STASH. The wide ranges and the A/A of 1.7–1.8 come from rounds where two labels landed in different modes. The java.lang.Object row is not bimodal.

Steady-state access on 64 already-built instances, cycled. Rows: reading 3 expandos; overwriting 3 existing expandos; a JS method; a Java method (hashCode()); a Java → JS call reading this.owner 1 time and 15 times. Each row runs on TS __extends instances and on .extend() instances. ns per operation, medians over rounds, resurrecting:

row TS, BASE TS, STASH TS STASH/BASE (A/A) .extend(), clean launch, BASE → STASH
expando read ×3 28.4 4.2 0.15 [0.14–0.16] (1.06 [0.99–1.11]) 5.0 → 4.7
expando write ×3 30.6 4.8 0.18 [0.15–0.26] (0.97 [0.90–1.05]) 5.5 → 5.5
JS method call 29.3 5.7 0.20 [0.19–0.25] (0.99 [0.96–1.10]) 5.6 → 5.8
Java method call 427 398 0.94 [0.92–1.02] (1.00 [0.99–1.00]) 393 → 396
Java → JS, 1 read 2231 2481 0.97 [0.82–1.81] (0.96 [0.86–1.88]) 2523 → 2550
Java → JS, 15 reads 2552 2580 0.87 [0.74–1.57] (0.94 [0.86–1.77]) 2576 → 2620
  • Resurrecting. With the old helpers each TS instance had a map of its own, so property and method access sites that see many instances went megamorphic: ~29 ns for what costs ~5 ns on a .extend() instance. With this change TS instances access at .extend() speed. The Java method row and both Java → JS rows are within noise. The Java → JS rows are dominated by the call itself (~2.5 µs) and are bimodal across launches.
  • Shared code. The .extend() column above comes from launches that only touch .extend() instances. When the same loops first ran over TS instances in the same launch, the .extend() instances paid for the polluted inline caches: with the old helpers, 29.6 / 29.1 / 39.0 ns for read / write / JS call. With this change they paid 10.1 / 6.8 / 6.1 ns. So the old helpers also slowed down other objects that share code with TS-extended instances.
  • Canary/all. No steady-state row moved beyond noise. Medians: expando read 0.89, write 0.95, JS call 0.83, Java call 0.98, Java → JS 1.01–1.03. Per-round A/A on these rows reached 1.35–1.87. Here, reads cost about 20–30 ns and writes about 550–890 ns with either helper and either kind of instance. The clean-launch .extend() control is flat (1.03 / 1.00 / 1.01 / 0.99). The first run's "use a built TS instance" row in canary/all showed STASH +40% on medians, but its launches were bimodal (1.4–3.0 µs in every label) and the ranges overlapped. These rows show no such regression.

Follow-up (not in this PR): ES classes and decorators

Native ES classes (class X extends android.view.View without down-leveling) can skip the helper entirely. That needs:

  • Runtime
    • ClassConstructorCallback handles new.target: it resolves the extended class (and caches it), uses new.target.prototype as the implementation object, and calls RegisterInstance on the receiver.
    • CreateExtendedJSWrapper and the canary rebuild use the class's own prototype.
    • The profiler's Wrap() forwards new.target.
    • The static binding generator recognises class X extends <native class>.
  • Core
    • An Android NativeClass decorator.
    • Enable isNativeESClassesEnabled for Android in packages/vite/helpers/nativeclass-transform.ts and in the webpack equivalent.

Does your commit message include the wording below to reference a specific issue in this repo?

No.

Related Pull Requests

Does your pull request have unit tests?

Yes. tests/testTypeScriptExtendedConstruction.js (registered in mainpage.js) covers TypeScript's ES5 output for a class extending a Java class:

  • instanceof the class and every Java class above it;
  • one prototype chain shared between instances;
  • field initializers kept as own properties, and per-instance state;
  • JS overrides called from Java with the instance as this;
  • super calls into the Java implementation;
  • inherited Java methods, and passing the instance to Java and back;
  • statics;
  • prototype chain and expandos of a Java-held instance after a collection;
  • constructors that forward their arguments with apply (a class without a constructor, and super(...args)).

The full suite (arm64 emulator, android-36.1 google_apis image, default resurrecting mode) passes on this branch: 1798 specs, 0 failures.

Summary by CodeRabbit

  • Improvements
    • Improved compatibility between JavaScript subclasses and native button classes, including constructor argument forwarding, inherited methods, and independent instance state.
  • Tests
    • Added coverage for subclass inheritance, JavaScript and native method dispatch, constructor behavior, and preserving native instances after garbage collection. The new test suite is included in the main page’s test sequence.

@coderabbitai

coderabbitai Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The native-class helpers now construct instances with Reflect.construct and link them to wrappers through a symbol-keyed property. A new Jasmine suite tests TypeScript-style Button1 subclasses, and the app test entry point loads the suite.

Changes: Native Subclass Construction

Layer / File(s) Summary
Construct and link native instances
test-app/app/src/main/assets/internal/ts_helpers.js
Parent.call and Parent.apply construct instances with Reflect.construct or new Extended(), then link them to wrappers. __native retrieves the linked instance and copies the wrapper’s own properties onto it.
Exercise subclass construction and behavior
test-app/app/src/main/assets/app/tests/testTypeScriptExtendedConstruction.js, test-app/app/src/main/assets/app/mainpage.js
The new suite checks subclass relationships, initialized and isolated fields, Java-to-JavaScript method dispatch, inherited methods, collection retention after garbage collection, static members, and constructor argument forwarding. The app test entry point loads the suite.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Refactor

Sequence Diagram(s)

sequenceDiagram
  participant Parent.call/apply
  participant Reflect.construct
  participant linkContainer
  participant __native
  Parent.call/apply->>Reflect.construct: construct Extended instance
  Reflect.construct->>linkContainer: pass constructed instance
  linkContainer->>linkContainer: store instance on wrapper symbol
  __native->>__native: retrieve linked instance and copy wrapper properties
Loading

Suggested reviewers: vtrifonov, vmutafov

Merge Risk: Minimal · up to f8cd9

This change moves TypeScript-extended native instances off the prototype-mode path to improve construction and access performance. TypeScript 2+ output is intended to behave as before, and the new tests cover that path. No merge-blocking risk was found in the supplied context.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: TypeScript-extended instances are kept out of prototype mode. The raw summary and objectives confirm that ts_helpers.js now constructs instances with Reflect.construct…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: TypeScript-extended instances are kept out of prototype mode. The raw summary and objectives confirm that ts_helpers.js now constructs instances with Reflect.construct and stores the native instance under a private symbol instead of assigning it as the prototype of the constructor's this. The title also uses a conventional perf(runtime) prefix and is concise and specific. The changeset also adds a new test suite and a load-order change, which the title does not mention, but that is expected for a title.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 78eaffc and f8cd9ee.

Files selected for processing: 2

  • test-app/app/src/main/assets/app/mainpage.js
  • test-app/app/src/main/assets/internal/ts_helpers.js

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 3 remain after this review.

edusperoni added a commit that referenced this pull request Nov 22, 2026
…onstructor (#2147)

### Description

TypeScript compiles a class without its own constructor (and
`super(...args)` at ES5 targets) to:

```js
function NamedThread() {
    return _super !== null && _super.apply(this, arguments) || this;
}
```

For native base classes, `__extends` in `internal/ts_helpers.js`
replaces `Parent.apply`. That helper built the constructor's argument
list as `[null].concat(args)`. `concat` spreads arrays but not an
`arguments` object, so the Java constructor got one argument, the
`Arguments` object, instead of the values passed to `new`. Creating such
a class with any argument threw `Cannot marshal JavaScript argument`.
Created with no arguments, it worked, because that path skips the list.

The helper now copies `args` with `Array.prototype.slice.call(args)`
before concatenating, which handles both an array and an `arguments`
object.

### Does your commit message include the wording below to reference a
specific issue in this repo?
No.

### Related Pull Requests
- #2148 rewrites the same `Parent.apply` line (it constructs with
`Reflect.construct` and no longer makes the instance a prototype), but
keeps `[].concat(args)`, so it still has this bug. Whichever of the two
merges second needs a one-line rebase to `Reflect.construct(Extended,
Array.prototype.slice.call(args))`.

### Does your pull request have [unit
tests](https://github.com/NativeScript/NativeScript/blob/master/running-tests.md)?
Yes. `testsForTypescript.js` adds
"When_a_typescript_class_without_a_constructor_is_created_with_arguments_it_should_pass_them_to_the_java_constructor":
TypeScript's output for `class NamedThread extends java.lang.Thread {}`,
created with `"named"` (checks `getName()`) and with no arguments.

The full suite (arm64 emulator, android-36.1 google_apis image) passes
on this branch: 1789 specs, 0 failures.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

<!-- coderabbit-ai-generated:v1 -->

## Summary by CodeRabbit

* **Bug Fixes**
* Fixed constructor argument handling for TypeScript-defined subclasses
of Java threads. Arguments are now correctly passed to the Java
constructor, allowing thread names to be set as expected. Instances
created with or without arguments are also correctly recognized as
instances of the subclass.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
@edusperoni
edusperoni marked this pull request as ready for review November 23, 2026 02:26
The TypeScript helpers made each native instance the prototype of the
constructor's own `this`. V8 gives every prototype a map of its own, so
each field store in the constructor missed its inline cache and copied the
map, and the instance kept a map no other instance shared.

The instance is no longer linked to the constructor's `this`; __native
finds it under a symbol instead. TypeScript 2+ output, which uses the
instance `super()` returns, behaves as before. Output from older
compilers, whose constructors keep working on their own `this` until
__native, can no longer reach the instance through it.

Construction also uses Reflect.construct instead of a bound function.
@edusperoni
edusperoni force-pushed the perf/extended-construct-no-prototype branch from 78eaffc to f8cd9ee Compare November 23, 2026 04:35
@edusperoni
edusperoni merged commit 8063043 into main Nov 23, 2026
11 checks passed
@edusperoni
edusperoni deleted the perf/extended-construct-no-prototype branch November 23, 2026 04:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant