Repository navigation
perf(runtime): keep TypeScript-extended instances out of prototype mode - #2148
Conversation
|
No actionable comments were generated in the recent review. Walkthrough
Merge Risk:
|
…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 -->
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.
78eaffc to
f8cd9ee
Compare
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 howinternal/ts_helpers.jsbuilds the instance.Root cause. For native base classes,
__extendsreplaces_super.call/_super.apply. The replacement created the Java-backed instance, then set it as the prototype of the constructor's ownthis(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:_this.a = ...) misses its inline cache and copies the map, about 1.4 µs per field;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.constructand never makes it a prototype. It stores the instance under a private symbol on the constructor'sthis, and__nativelooks for it there. TypeScript 2+ output (var _this = _super.call(this, ...) || this; ...; return _this;) uses the instancesuper()returns directly, so it behaves as before.Reflect.constructalso replaces theFunction.prototype.bind.applyconstruction.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 ownthis. Thatthisused to reach the Java instance through its prototype; it no longer does.return __native(this)still works:__nativemoves the fields set onthisto the instance and returns the instance. The existing specs intestsForTypescript.jsthat use this shape still pass._super.call(this)and__native(this), calling Java methods onthisor passingthisto Java no longer works.__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).BASE= the previous helpers;STASH= this branch's helpers. Both APKs contain the samelibNativeScript.so; onlyinternal/ts_helpers.jsdiffers.BASEbis theBASEAPK under a second label, as an A/A control.cmd package compile -m speed -f), the first launch after each install was discarded, and label order rotated by round. Each cell is the median over launches of the per-launch median.main, so canary mode can be compared.resurrectingis the default mode; canary/all is the mode where every wrapper gets a canary.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..extend()floorA/A (
BASEbvsBASE) 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:
java.lang.Object.extend()construct (control)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.Objectrow 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 readingthis.owner1 time and 15 times. Each row runs on TS__extendsinstances and on.extend()instances. ns per operation, medians over rounds, resurrecting:.extend(), clean launch, BASE → STASH.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..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..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.Viewwithout down-leveling) can skip the helper entirely. That needs:ClassConstructorCallbackhandlesnew.target: it resolves the extended class (and caches it), usesnew.target.prototypeas the implementation object, and callsRegisterInstanceon the receiver.CreateExtendedJSWrapperand the canary rebuild use the class's own prototype.Wrap()forwardsnew.target.class X extends <native class>.NativeClassdecorator.isNativeESClassesEnabledfor Android inpackages/vite/helpers/nativeclass-transform.tsand in the webpack equivalent.Does your commit message include the wording below to reference a specific issue in this repo?
No.
Related Pull Requests
_super.apply(this, arguments)dropping the arguments ([null].concat(arguments)passes theArgumentsobject itself). This PR rewrites the sameParent.applyline but keeps[].concat(args), so it does not fix that. Whichever merges second needs a one-line rebase toReflect.construct(Extended, Array.prototype.slice.call(args)).main.Does your pull request have unit tests?
Yes.
tests/testTypeScriptExtendedConstruction.js(registered inmainpage.js) covers TypeScript's ES5 output for a class extending a Java class:instanceofthe class and every Java class above it;this;supercalls into the Java implementation;apply(a class without a constructor, andsuper(...args)).The full suite (arm64 emulator, android-36.1 google_apis image, default
resurrectingmode) passes on this branch: 1798 specs, 0 failures.Summary by CodeRabbit