4 ms·
1. Unsafe blocks only apply to shared structs, and shared structs are basically only relevant with unsafe blocks. This is somewhat two proposals in one: Shared
by aapoalas 2y ago
1. Unsafe blocks only apply to shared structs, and shared structs are basically only relevant with unsafe blocks. This is somewhat two proposals in one: Shared structs which require more restrictions to be shareable at all but are still kind of unsafe (because data races), and then unshared structs which adopt those same restrictions without being shareable. In exchange, they become much easier to optimise for engines. Unsafe blocks are there for the first part, unshared structs kind of come as a two-for-one prize on top.
2. Indeed, structs are rather an entirely different track to classes. Only the syntax is borrowed from them.
3. There's a bunch of stuff that the engine will do for you to try make your code faster. The most important thing (arguably) is inline caching: When you access `foo.bar` inside a function, your engine will remember the "shape" of the `foo` object (if it is an object, that is) and where the property `bar` was found inside of it. Unfortunately, objects tend to be pretty fluid things, so the shape of an object changes. This creates a "transition" graph of shapes, and it's pretty hairy stuff. It's also a source of memory safety bugs in browsers, as browsers want to avoid re-checking the shape of an object if it cannot have changed but this is mostly a manual optimisation, and eg. Proxies really make it so nearly everything can change an object's shape. A misapplied shape caching optimisation is easy to turn into an arbitrary read/write primitive, which is then a great way to escape the sandbox.
Imagine then that an object type existed that could be primitively guaranteed to never change it's shape? Oh, the engine would loooove that. No worries about memory safety mistakes, just cache the shape when you first see it and off to the races you go!
This applies doubly to any prototypes (which here are proposed to be only sealed; I'd personally want to see them frozen so that not only the shape can be cached but also the value): An object's shape may stay the same but the prototype may change with key deletions and additions. This means that looking up that function to call for `obj.hasOwnProperty("key")` needs to, theoretically, be redone every time. Engines of course optimise this into a fairly complex linked list of booleans, but by golly wouldn't it be easier if the engine could just statically cache that the property we're looking for is found in this particular prototype object at a particular memory offset?
Source: I lurk around in some adjacent circles, and am writing my own JavaScript engine built with potentially peculiar ideas about what makes good JavaScript.