22 ms·
Proposal: JavaScript Structs
- _9hey 2y agoThe scope of this proposal is too large. If it comes down to preference, I'm not a rust rust fanboy but I think they got the struct/impl paradigm right.
- whizzter 2y agoNot sure this is a good idea or not, for one it'd be awesome for doing performance oriented and threaded code in JS/runtimes, the idea seems related to how C# struct's already work (and tuples under the hood). Interop with WASM code might also be simplified if struct-like access was a built-in. The bad is that people wouldn't necessarily be prepared for their semantics (are they value or reference based?), how to shared prototypes between environments (mentioned as problem in the proposal itself), not entirely sure if this proposal would add to the complexity vs security for spectre like attacks. It'd be useful, but worth it is another question? (And would all major players see interest in it? esp considering that it'd need to be "JSzero" level propsal if they go in that direction. (There was a post here a few days ago about layering runtimes with JS0 being the core with everything else being syntax transforms on top).
- pjmlp 2y agoNote that the idea isn't unique to C# structs, other GC enabled languages have similar capabilities.
- egeozcan 2y agoHuh, I thought that most work that used to use workers switched to Webassembly. Talking about JS proposals, I'm looking forward to this one: https://github.com/tc39/proposal-record-tuple https://github.com/tc39/proposal-record-tuple Records and tuples can make a lot of logic much more easier to read, and way less fragile. Not sure how they would play together with the shared structs though.
- deleted 2y ago[deleted]
- AprilArcus 2y agoI don't think R&T will ever ship at this point, since the browser vendors are apparently unwilling to absorb the complexity that would be required to add new primitive types with value semantics.
- sjrd 2y agoI've been following that proposal closely, and even (unsuccessfully) tried to contribute suggestions to it. I think what's killing it is that the authors of the proposal won't accept arbitrary values as fields of R/T, but all the potential users are saying that they won't use R/T if they can't put arbitrary values in them. The reluctance of the authors is due to backward compatibility with sandboxed "secure" JavaScript (SES). That said, every other language in existence that has immutable structs and records allows to put arbitrary values in them. So it's at a standstill, unfortunately.
- zarzavat 2y agoIf you allow arbitrary values, what's the difference between a record and a frozen object? I thought that the whole point is to have guaranteed deep immutability, which you can't have if it's got arbitrary objects in it.
- maxdamantus 2y ago> If you allow arbitrary values, what's the difference between a record and a frozen object? The behaviour of equality. Frozen objects are already considered to have unique identities, in that `Object.freeze({}) !== Object.freeze({})` even though both objects are otherwise indistinguishable. This behaviour can't be changed and it relates to the fact that `Object.freeze(a) === a`. > I thought that the whole point is to have guaranteed deep immutability Not really. The whole point apparently according to most people[0] is to have composite values that don't have unique identities, so they fit in with all the existing comparison operations (eg, `===`, `Map`, `indexOf`, `includes`) just as you can do with strings. Immutability is a prerequisite for this, since if `a` and `b` are mutable, mutating `a` might be different to mutating `b`. Thinking again about strings, equality works because strings are immutable: const foo = "foo", bar = "bar"; const a = foo + bar; const b = foo + bar; a === b; // true Implementations will typically use different underlying memory allocations for these strings[1], but at a language level they are considered to be the same value. If it were possible to modify one of the strings (but not the other) using `a[0] = "x";` it would mean `a` and `b` are not equivalent so should not be considered equal. As explained here[2], deep immutability is not necessary for this behaviour. In my opinion guaranteed "deep immutability" is not generally useful/meaningful (if you have a particular use case, feel free to share it). In theory it's not possible to enforce "deep immutability" because someone can always refer to something mutable, whether that's an object reference or a number indexing a mutable array. If you really do want something that guarantees a certain notion of "deep immutability", this concept seems somewhat orthogonal to records/tuples, since there are existing values (eg, strings and numbers) that should be considered deeply immutable, so you'd expect to have a separate predicate[3][4] for detecting this, which would be able to effectively search a given value for object references. In case you're interested I tried to summarise the logic behind the rejection of this behaviour[5] (which I disagree with), but it's very much a TLDR so further reading of linked issues would be required to understand the points made. Interestingly, this post is on an issue raised by the odd person that actually tried to use the feature and naturally ran into this restriction. Sorry for this massive wall of text, but I think it's hard to capture the various trains of thought concisely. [0] https://github.com/tc39/proposal-record-tuple/issues/387#issuecomment-1953271467 https://github.com/tc39/proposal-record-tuple/issues/387#iss... [1] https://github.com/tc39/proposal-record-tuple/issues/292#issuecomment-1080383876 https://github.com/tc39/proposal-record-tuple/issues/292#iss... [2] https://github.com/tc39/proposal-record-tuple/issues/292#issue-1124661969 https://github.com/tc39/proposal-record-tuple/issues/292#iss... [3] https://github.com/tc39/proposal-record-tuple/issues/292#issuecomment-1082557590 https://github.com/tc39/proposal-record-tuple/issues/292#iss... [4] https://github.com/tc39/proposal-record-tuple/issues/206 https://github.com/tc39/proposal-record-tuple/issues/206 (I believe sjrd (GP) earlier independently came up with the same function name and behaviour somewhere in this thread, but GitHub seems to be failing to load it) [5] https://github.com/tc39/proposal-record-tuple/issues/390#issuecomment-2348971939 https://github.com/tc39/proposal-record-tuple/issues/390#iss...
- modeless 2y agoHuh, no types. So every field is 8 bytes I guess? I suppose if you want a defined/packed memory layout you can already use SharedArrayBuffer and if you want to store objects in it you can use this BufferBackedObjects library they linked. https://github.com/GoogleChromeLabs/buffer-backed-object https://github.com/GoogleChromeLabs/buffer-backed-object I also expect that in browsers this will have the same cross-origin isolation requirements as SharedArrayBuffer that make it difficult to use.
- syg 2y agoTo be more precise, aligned to whatever size such that you can guarantee field writes that don't tear. Pointer-aligned is a safe bet. 4-byte aligned should be okay too on 64bit architectures if you use pointer compression like V8 does. What kind of types did you have in mind? Machine integers and "any" (i.e., a JS primitive or object)? And yes, in browsers this will be gated by cross-origin isolation.
- modeless 2y agoIf the memory layout is fixed and fields are untyped then every field must be at least 8 bytes to potentially hold a double precision floating point value. There would clearly be value in adding typing to restrict field values to 1 or 2 or 4 byte integers to allow packing those fields. But I can see that it would add complexity.
- syg 2y agoOnly if your implementation holds doubles without boxing them. V8 boxes doubles, but JSC and SpiderMonkey do not.
- Jcampuzano2 2y agoJS devs - do everything but write in another language challenge level: Impossible.
- bastawhiz 2y agoCall me when browsers support another language. What are we going to use? CSS?
- modeless 2y agowasm "but wasm has to call JavaScript to use browser APIs" WasmGC is shipped in Chrome and Firefox and enabled by default in WebKit nightly
- johnfn 2y agoLet me know when WASM has a dev workflow that gets a change to your browser 1/10th as fast as Vite + TypeScript + React.
- modeless 2y agoThe web is undefeated in iteration time for sure. There are some native workflows that approach it with hot code reloading, but I'm not aware of anyone doing that for wasm yet.
- xpe 2y agoI will grant that fast iteration is beneficial. But for me, under 10 seconds is usually fast enough. (For example, I don't think I would care too much when comparing 0.5 vs 5 second builds.) I personally care a lot more about having a confidence-inspiring language and ecosystem. In my experience with Rust and WASM (with various tools such as Dioxus), I find myself caring a lot more about the WASM ecosystem and browser evolution/improvement. For example, at bottom, the JS interop feels pretty sub-optimal. Calling this "hcky" might even be deserved: I'm talking about memory serialization between JS-land and WASM-land. As I understand it, we may see significant improvement under the hood in the next few years. (I'm not an expert on the particular proposals, their adoption, etc. Please weigh in if you have a better sense.)
- connicpu 2y agoThe general idea of types with a fixed layout seems great, but I'm a lot more dubious about the idea of unsafe blocks. The web is supposed to be a sandbox where we run untrusted code and with pretty good certainty expect that it can't crash the computer. Allowing untrusted code to specify "hey let me do stuff that can cause data races if not done correctly" is just asking for trouble, and also exploits. If shared structs are going to be adopted I think they probably need to be immutable after creation, or at the very least only modified with atomic operations.
- jitl 2y agoThe unsafe block doesn't actually do anything at all. It's just pointless cargo-cutling from Rust.
- jsheard 2y agoIsn't it really no different to what you can already do with WASM threads though? C/C++ or unsafe Rust compiled to WASM can have data races, but the worst it can do is crash the WASM instance, just like how you can have use-after-frees or out-of-bounds array accesses in WASM but the blast radius is confined to the instance. Granted, a JS runtime is significantly more complex than a WASM runtime so there is more room for error.
- titzer 2y ago> crash the WASM instance I guess it depends on how you get to said crash, but no, data races on Wasm shared memory cannot "crash" anything. At worst racy reads/writes can produce garbage (primitive) values and put garbage bits into memory locations involved in the accesses. Putting garbage bits into a Wasm memory could lead to a program's logic having bugs (e.g. it could then try to access out of bounds or trap for another reason), but the accesses themselves can't crash anything.
- leoh 2y agoThis is a good point, I think, in that — on account of wasm — there is really an opportunity for new languages in the browser
- 2y ago
- bastawhiz 2y agoI initially didn't like the high level idea, but I warmed up to it. My only concern is that the constructor isn't guaranteed to define the same fields with the same types, which kind of defeats the point. I'd improve this proposal in two ways: 1. Explicitly define the layout with types. It's new syntax already, you can be spicy here. 2. Define a way for structs to be directly read into and out of ArrayBuffers. Fixed layout memory and serialization go hand in hand. Obviously a lot of unanswered questions here but that's the point of the process. The unsafe block stuff, frankly, seems like it should be part of a separate proposal.
- jtolmar 2y agoI agree; the point of a struct type would be to allow a compact memory representation, and you're not going to get it if your constructor can do if(someArg) { a = 1; } else { a = 1; b = 2; }. You don't strictly need known/consistent types, but it sure helps, since otherwise everything needs to be 8 bytes. I don't think a way to read into and out of ArrayBuffers is possible, since these can have pointers in them. I think it needs a StructArray class instead, so there's a way to actually make a compact memory array out of all of this.
- bastawhiz 2y ago> You don't strictly need known/consistent types, but it sure helps, since otherwise everything needs to be 8 bytes. Arguably that's worse than what the runtime is able to do today already with hidden classes. > I don't think a way to read into and out of ArrayBuffers is possible If you know all the types and only allow structs and primitives, you could use relative pointers to encode the 2nd+ references to structs that appear more than once in the encoded object. You'd need a StructArray for efficient arrays, but a linked list would encode pretty compactly. But you're very right.
- weego 2y agoIt's hard to take anyone concerned about the 'performance ceilings' in javascript object creation seriously at this point.
- skrebbel 2y agowhy?
- wiseowise 2y agoJS bad. /s
- aardvark179 2y agoGive developers an alternative to classes that favors a higher performance ceiling and statically analyzability over flexbility. Is an entirely reasonable goal. Object shape in JS tends to go through a fixed pattern of mutation immediately after construction and although that can sometimes be analysed away by the JIT there are a lot of edge cases that can make that tricky. You may not care, but I bet almost everybody who has actually worked on a JS engine does, and has good reasons for doing so.
- leetharris 2y agoI am not sure how to really refine this thought I have had, but I have this fear that every language eventually gets so bloated and complicated that it has a huge barrier to entry. The ones that stand out the most to me are C# and Typescript. Microsoft has a large team dedicated towards improving these languages constantly and instead of exclusively focusing on making them easier to use or more performant, they are constantly adding features. After all, it is their job. They are incentivized to keep making it more complex. The first time I ever used C# was probably version 5? Maybe? We're on version 12 now and there's so much stuff in there that sometimes modern C# code from experts looks unreadable to me. One of the reasons I have so much fun working in node/Javascript these days is because it is simple and not much has changed in express/node/etc for a long time. If I need an iterable that I can simply move through, I just do `let items = [];`. It is so easy and hasn't changed for so many years. I worry that we eventually come out with a dozen ways to do an array and modern code becomes much more challenging to read. When Typescript first came out, it was great. Types in Javascript are something we've always wanted. Now, Typescript is on version 5.6 and there is so much stuff you can do with it that it's overwhelming. And nobody uses most of it! This is probably just old man ranting, but I think there's something there. The old version I used to debate about was C vs C++. Now look at modern C++, it's crazy powerful but so jam packed that many people have just gone back to C.
- pjmlp 2y agoC23 has just been ratified, and C2y has already quite a few proposals. Programming languages are like any other software product, evolution or stagnation. Eventually they might implode, however whatever comes after will follow the same cycle yet again.
- PedroBatista 2y agoI mean.. After ES6 with classes what is JavaScript anyway? Just bring Structs too, the more the merrier.
- zanethomas 2y agoI know, right? Fortunately we can still aren't forced to use all the 'enhancements'.
- tengbretson 2y agoNahhh
- digger495 2y agoThey should just go write golang, if this is what they want.
- rglover 2y ago[flagged]
- mmastrac 2y agoPlease don't do this. These summaries literally add nothing to the discussion.
- dartos 2y agoThey add at most nothing ;)
- deleted 2y ago[deleted]
- dartos 2y agoFar too long to be a TLDR. Especially since it’s AI slop. I’d either want one or two sentences or just read the first party source.
- afavour 2y agoI feel conflicted. Working with multithreaded stuff in JS is a huge PITA. This would go some way to making things easier. But it also feels like it would radically complicate JS. Unsafe blocks? Wow-eee. With the rise of WASM part of me feels like we shouldn't even try to make JS better at multithreading and just use other languages better suited to the purpose. But then I'm a pessimist.
- akira2501 2y agoI read this and think "can't we just make freezing objects less expensive?" Otherwise, that's all this seems like to me, a class where all instances are automatically frozen. Which is a great semantic, but they expose way too much of the internals, in this proposal, to achieve that. Modern development is so goofy.
- afavour 2y agoPuts me in mind of that meme with the beginner -> intermediate -> expert chart with something like Rust Beginner: just clone everything Intermediate: work out every intricacy that allows us to use multiple lifetimes Expert: just clone everything This proposal feels like it's in the middle.
- andai 2y ago> With the rise of WASM part of me feels like we shouldn't even try to make JS better at multithreading and just use other languages better suited to the purpose. I think TS is a negative influence on JS, because now instead of saying "maybe we should fix the JS type system" they just say "no need to fix what's broken, people who care will just use TS anyway" (even though TS can only do so much). On the other hand, TS mainstreamed the idea of typed JS (well, ActionScript did that decades ago, but somehow no one noticed or cared?), so it's also a positive influence? Most people are drawn to WASM because "I can do frontend stuff without writing JS!" but for the most part that's not true, and in my experience the problems introduced by the indirection and interop, and the complexification of the mental model, and the bloating of the build system (and its fragility), were not worth it and I just switched back to TS. So I do really wish that JS would be improved -- it remains inescapable -- especially with regard to fixing fundamental design flaws rather than just adding more shiny stuff on top.
- szastamasta 2y agoPlease stop. What a nonsense. JS is a dynamic language where everything is a Hashtable. It will never be really fast as your structs won’t be in single cacheline, you won’t be able to calculate field address during compile time by pointer offsets. There’s no simd, no multithreading, no real arrays. JS is such a simple, dynamic language. It should just stay this way. Please stop bloating it with every feature that’s trendy this year. We already have classes that we didn’t need. We don’t need structs for sure.
- tantalor 2y agoHigh performance applications are already being written that depend on features like shared memory, but because the language has poor support for them then developers have to use ugly workarounds. This proposal solves that with built-in support. >It should just stay this way Counterpoint: JS has been evolving significantly, look at ES6 and ES8 in particular if you need help finding examples.
- rty32 2y agoExactly. Without new features and syntaxes people would still be doing MyClass.prototype.method = function () { } like idiots. Such a meaningless argument for preventing progress.
- szastamasta 2y agoNobody needs classes nor prototypes in JS. Objects + functions is more than enough. I stopped using these few years ago and miss nothing.
- meindnoch 2y agoLeave. The. Language. Alone.
- BoingBoomTschak 2y agoThe similarity with CL's divide between structs and classes is uncanny; especially with ((:type vector) :named).
- wetpaws 2y ago[dead]
- dangoodmanUT 2y agoI thought it said "Proposal: JavaScript Sucks" and was not surprised by the number of upvotes from HN
- PeterWhittaker 2y ago(Wipes away tears of laughter) I needed that! [1] [2] [1] just got some bad news [2] all in all, I love working in JS when I have to, but I’ve worked in it long enough to know of at least very many of the foot guns.
- Alifatisk 2y agoWhy couldn’t you just write a paragraph instead of using some citing system for formulating your sentence?
- Philpax 2y agoThey're footnotes and are meant to be read as supplementary notes to the core message.
- Alifatisk 2y agoBut we already have a way for supplementary notes, it's by using parentheses? Like this: Today I went for a walk (which I don't usually do), and I saw a squirrel. Or have I been doing it wrong?
- syg 2y agoWell I'm trying to make it suck less.
- pwdisswordfishz 2y agoAs in https://suckless.org/sucks/web/ https://suckless.org/sucks/web/?
- nikeee 2y agoWhen reading the proposal title, I thought that this is for interop with WASM. Having fixed-size structs where every field has a wasm-related type would be beautiful for interop. Just a wasm function can just return or receive an instance of a typed struct. No more reading the result using a DataView or something like that. We have to use something like BufferBackedObject for that.
- lxe 2y ago𝅘𝅥𝅮𝅘𝅥𝅮𝅘𝅥𝅮𝅘𝅥𝅮 They've got decorators, record tuples, shadow realms, and rich rekeying Dynamic imports, lazy modules, async contexts now displaying JSON parsing, destructure privates, string dedenters, map emplacers Symbols pointing, pipe operators, range iterators, code enhancers Eager asyncs, resource tracking, strict type checks, and error mapping Phase imports, struct layouts, buffering specs for data stacking Temporal zones, buffer edges, chunking calls for nested fragments Explicit locks, throw expressions, float16s for rounding segments Base64 for typed arrays, joint collections, parsing pathways Atomic pauses, void discarding, module scopes for seamless relays Math precision, tuple locking, module imports, code unlocking Source phase parses, regex bounds, iterators kept from blocking Iterating, winding modules, atomic gates with locks unbound Helper methods, contexts binding, async helpers, code aligning Soffit panels, circuit brakers, vacuum cleaners, coffee makers Calculators, generators, matching salt and pepper shakers I can't wait, (no I) I can't wait (oh when) When are they gonna open the door? I'm goin' (yes I'm) goin', I'm a-goin' to the ECMAScript Store
- paulddraper 2y ago10/10
- i007 2y ago// Step 1: Convert JSON object to string const jsonObject = { name: "John", age: 30 }; const jsonString = JSON.stringify(jsonObject); // Step 2: Convert the string to binary data const encoder = new TextEncoder(); const encodedJson = encoder.encode(jsonString); // Step 3: Create a SharedArrayBuffer and a Uint8Array view const sharedArrayBuffer = new SharedArrayBuffer(encodedJson.length); const sharedArray = new Uint8Array(sharedArrayBuffer); // Step 4: Store the encoded data in the SharedArrayBuffer sharedArray.set(encodedJson); Now you can use Atomics, no? https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- winrid 2y agoThe thing I like about this is when I get a heap dump I could get names for things instead of "object shapes", which would be cool.
- alkonaut 2y agoFixed layout structs seem like a no brainer and a natural extension of the typed arrays. It’s strange that both Java and Jacascript went so long without them. Interacting with many APIs (webgpu, FFI, …) quickly becomes really unpleasant if you can’t control data layout.
- zanethomas 2y agoI don't understand the need for the ever-growing list of "enhancements" to JS. Take Class for example. Class is entirely unnecessary and, essentially, tries to turn JS into a class-oriented language from its core which is object-oriented. I never create classes. I always create factory functions which, when appropriate, can accept other objects for composition. And I don't use prototypes, because they are unnecessary as well. Thus sparing me the inconvenience, and potential issues, of using 'this'. In my dreams those who want to turn JS into c# or Java should just create a language they like and stop piling on to JS. But, at least so far, the core of JS has not been ruined. That said, there are some new features I like. Promises/async/await, Map, Set, enhancements to Array being among them. But to my way of thinking they do not change the nature of the language in any way.
- imbnwa 2y ago>And I don't use prototypes, because they are unnecessary as well. Thus sparing me the inconvenience, and potential issues, of using 'this'. Eh, prototypes share, instead of create, method references. I guess you can use delegate objects too though unless you're just doing pure functions.
- zanethomas 2y agoSure, but imo unless one is creating very many objects each with their own set of functions it's not really a significant issue. Sometimes programmers spend way too much time optimizing code which doesn't really need it. In my experience how data is structured is almost always the most important factor when it comes to performance. Good data structure + simple code === performance.
- wruza 2y agoOtoh, I create classes, use prototypes and it’s natural and useful in many of my cases. In my dreams those who want to turn JS into c# or Java should just create a language they like and stop piling on to JS. We could even share this dream if browser vendors weren’t such whos the boss iam da boss when it comes to extensions and alternatives. So we have to live in a common denominator, which surprisingly isn’t as bad as it could be, really.
- ricardobeat 2y agoI thought we were done shoehorning all possible CS concepts into javascript?
- rattray 2y agopersonally I'm super excited to see this -- have been wanting something along these lines for quite some time.
- lifthrasiir 2y agoCan see "why", but I can't really see why a new syntax is warranted. This feature is expected to be used infrequently and probably has to be defined as an ECMAScript extension only in order to put it into WebAssembly. A "fake" prototype that indicates strictness should be enough for implementations (and polyfills). There are many other issues but that is glaring enough to be pointed out.
- voidr 2y agoMost of the JavaScript developers I've encountered recently refuse to use Map, and if you dare use it, they will say that it's complicated code and premature optimisation before even making an attempt to understand it. I feel like trying to add fast data structures into JavaScript is futile, I think at this point it would be better to make it easier for JavaScript and the browser to interface with faster languages. The only thing I would add to JavaScript at this point is first class TypeScript support so that we can ditch the transpilers.
- khana 2y ago[dead]
- deleted 2y ago[deleted]
- fergie 2y agoMaybe I'm missing something, but this seems to add very little. Please correct me if I am missing something. 1) Struts are encouraging a coding style that restricts what you can do. This inflexibility is then negated by adding unsafe blocks? 2) Struts don't, as far as I can see, address any of the _actual_ weaknesses of js classes- such as not being able to create aysnc constructors. 3) The cited performance benefits seem a bit strange. JS has no access to pointers or memory by design, so I don't understand why struts will automatically make things faster. Surely it makes more sense to refine the v8 engine, or even focus on WASM rather than adding syntactic sugar to vanilla js. That said- props to people who care enough to write a proposal- and if I am missing the point of struts, sorry for the negativity.
- noman-land 2y agoStructs
- aapoalas 2y ago1. 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.
- antifa 2y agoI just want structs (in regards to impact on the garbage collector).
- flippy_flops 2y agoIs there a way to "vote" on these types of proposals? (Just asking for a friend who sees this as bloat and does not want to deal with other people's code which uses this unnecessarily)
- talkingtab 2y agoA better title "A proposal for Shared Memory Multi-threading". The term "struct" has a meaning in the C language that is somewhat misleading since the purpose here is not organization, but rather to enable shared memory. In my experience, the positive of JavaScript over other languages I have used- COBOL, Fortran, assembly, C, C++, Java - is the fine balance it has between expressibility and effectiveness. I am not opposed to shared memory multi-threading, but question the cost/benefit ratio of this proposal. As many comments suggest, maintaining expressibility is a high priority and there are plenty of gotchas in JavaScript already. As an example, I find the use of an upfront term like "async" to work quite well. If I see that term I can easily switch hats and look at code differently. Perhaps we could look at other mechanisms, using the term "shm", over a new type, but what do I know? [edit for clarity since I think faster than I can type]
- aapoalas 2y ago@syg If you happen around to answer more questions: Why going with only Sealed prototypes for structs? Personally, I would assume that with static initializer blocks we could well go with "initially Sealed" with "Frozen once class initialization completes". ie. Make the last step of "StructDefinitionEvaluation" AO "SetIntegrityLevel(F, FROZEN)". This way I'd assume eg. decorators would be usable on struct fields and methods, but engines would be safe to cache prototype method lookup result values without any validity cell mechanics. I would assume this could make prototype method calls on structs very fast indeed.
- baxuz 2y agoThis looks like it's going to be a great fit for emscripten, especially multithreaded.
- davidhs 2y agoWhat a mess this language is becoming.
- ActionHank 2y agoI think that there is a spilling over of financially incentivized "innovation" stemming from the companies that are involved in the browser \ web space. If you are fairly senior or aiming for some sort of promotion this is the sort of thing that looks great on your resume. I doubt that it is driven by a desire to help consuming devs build better quality products more quickly or easily.
- leoh 2y agoNeeds a re-entrant mutex?
- ralmidani 2y agoMy head is spinning after skimming the sections on shared memory, locks, mutexes, etc. Implementation and adoption would probably be a decade-long saga. Not to mention teaching folks when to use these and how to use them correctly. In e.g. Elixir these are non-issues. Please, just give us declarative structs that are immutable by default (if they’re really needed, make constructors and mutability opt-in). Isn’t the trend already toward more FP in JS?
- dvlsg 2y agoThere's technically a proposal to add immutable lists and records floating around somewhere. I think it's kind of old at this point. I'm still hoping it makes it through, though.
- andai 2y agoA stricter, faster subset of JS would be very welcome, which seems to be what the unshared struct part of this proposal provides. By the way, doesn't V8's optimizer already do something like this internally? I read one of their tech blogs back in the day that explained how they analyze the structure of objects and whenever possible, compile it to the equivalent of a C++ class. I guess doing it explicitly makes the optimizer's job much easier -- the more guarantees you give it about what won't happen, the more optimizations it's free to make.
- ivanjermakov 2y agoNot JS, but quite the same niche is where AssemblyScript sits: https://www.assemblyscript.org/ https://www.assemblyscript.org/
- k3vinw 2y agoI love JavaScript! It’s such an exciting development experience loaded with surprises! I was just thinking the other day how cool it would be if it had unsafe blocks like in Rust. What an exciting time to be alive!
- barrystaes 2y agoHappy to see this effort. When applying ReactJS in webdev after doing all kinds of engineering in all kinds of (mostly typed) languages in many runtimes, I was so surprised that JS did not actually had a struct/record as seen in C/Pascal. Everything is a prototype that pretends its an object, but without types and pointers, and abstraction layers that added complexity to gain backwards compatibility. Not even some object hack that many OO and compiled languages had. ES did not add it either, and my hopes where in WebAsm. This proposal however seems like the actual plan that i’d like to use a lot. A lot of the code complexity was to get simple guarantees for data quality. The alternative was to not care, either a feature or caveat of the used prototype model.
- sdsds121dsds 2y agowhat