145 points · by EntICOnc · 5y ago · 124 comments
I'm the author of the articles, btw.
What's amazing is that that talk came out several months before V8, the first JavaScript engine that actually used the ideas in that talk. But, of course, that talk was possible because V8 was already under development.
First, all the stuff about tracing and trace trees is kind of obsolete. SpiderMonkey abandoned TraceMonkey a long time ago. (To the best of my knowledge, V8 never implemented a tracing JIT at all.) The problem with tracing is that you can get really good performance when everything goes right, but it's brittle. There's a reference in the talk to how implementations of the Game of Life can have exponential blow-up, for example. You can usually fix any individual pathological case, but the inherently exponential number of possible paths through a program make it difficult to completely eliminate weird performance cliffs.
If your goal is to maximize performance on a known set of benchmarks, go wild. If you want a robust engine that can handle whatever weird code the web is throwing at you, tracing JITs are (as far as I can tell) a dead end.
(Counterpoint: LuaJIT seems to be doing alright with tracing, although it may just solve the problem by punting to the programmer: https://github.com/lukego/blog/issues/29. That's more feasible when you don't have multiple engines with performance cliffs in subtly different places.)
Second, the idea that JIT-compiled code can be faster than AOT-compiled code has been floating around for a long time, but I don't think it really holds in the general case. Doing work at runtime isn't free: not just time spent compiling, but also time spent profiling and validating that your speculative optimizations continue to be correct.
SpiderMonkey had a top-tier optimizing compiler, IonMonkey, that got pretty darn close to native code on hot benchmark loops. We tracked whole-program information to ensure that type checks could be elided in inner loops. (For example, if the `x` property of a certain set of objects only ever contained 32-bit integers, then we could unbox it without checking the type. If any code elsewhere ever stored a non-integer value in that property, we would notice and invalidate the optimized code.)
We threw IonMonkey away, because it was too brittle. In practice, real-world code falls off the happy path often enough that we got better performance by accepting that even your highly optimized JS code will include some runtime checks. Invalidation and recompilation are real costs. So is the upkeep of all the global data necessary to support Ion. There's an engineering tradeoff between pushing up the performance ceiling and bringing up the performance floor; we've been happy with our choice to shift focus more towards the latter. Our numbers are down on artificial benchmarks, but it seems to have paid off in real-world performance. (Also, bugs in the optimizing compiler are significantly less likely to be exploitable.)
A lot of really smart people have done some incredible work on the JVM. Nevertheless, I'm still not aware of any code written in Java instead of (say) C++ or Rust because Java was faster. I think it's more accurate to say that JIT compilation can be fast enough that the other advantages of the language can make it the right choice.
I hadn't thought about this, but I love this sentiment
I often write micro benchmarks to see if something is faster one way or another. I often find one browser or another to be 3x to 10x faster in a certain micro benchmark.
A big issue is, most websites don't need perf AFAICT. Of the sites I use regularly (HN, Stack Overflow, GMail, Gdocs, GSheets, Facebook, Messenger, Slack, Reddit, github, maybe only gsheets and gdocs need any real perf.
The place where perf is needed is things like three.js, playcanvas, babylon.js, unity -> html, etc... And on those AFAIK, Chrome almost always wins, probably, because it's GPU support is multi-process
Microbenchmarks are tricky because it's very easy to measure something other than what you intend: differences in inlining heuristics, say.
In the long run, I expect performance-critical websites to migrate to webassembly.
Although I’d note that performance is utterly important for normal applications as well. Being noticeably snappy and prompt is great for UX.
Has there been any consideration to create AI to work around pathological cases in tracing?
If compiling is done on a secondary thread, aren't you then reaping all the benefits of JIT optimization while still not paying the penalty on the actual JS execution thread?
Why throw away optimized code? Why not add a type check on the parameters and then dispatch to the highly-optimized code version based on the parameter count and types?
None of which I'm aware.
> If compiling is done on a secondary thread, aren't you then reaping all the benefits of JIT optimization while still not paying the penalty on the actual JS execution thread?
Compilation can be done off-thread, but to decide what to compile you have to do some on-thread data collection, and until you're done compiling you have to run in a lower tier. Also, you usually have to do some work to make sure that your speculative optimizations are correct: for example, an inline cache needs to verify that you've got a cache hit.
> Why throw away optimized code? Why not add a type check on the parameters and then dispatch to the highly-optimized code version based on the parameter count and types?
Optimized code is optimized under a certain set of assumptions, which can be propagated through a function. For example, if the value that we read from an object's property is always an int, then we can do integer arithmetic with it afterwards. If we suddenly load a string or a double, then a bunch of downstream code will also be invalid. It's cheaper and less error prone to start over, rather than trying to track all the places that depend on a particular piece of information.
If you only specialize individual operations based on the type input, and don't propagate type information between operations, they you've basically got polymorphic inline caches. That's what we use in our baseline compiler.
I don't think JS is as fast as traditional compiled languages. Java/C# are faster, Go is faster, OCaml/Haskell are faster, Common Lisp is faster, C/C++/Rust are faster.
https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
I'd imagine that most scripts in websites are static assets, i.e. change rarely and have cache headers that support storage. Couldn't you make use of that to save a compiled version of the script together with the cached file? So when the page is loaded again, scripts are already compiled.
Is something like this done in practice?
TypeScript's type system is so utterly broken that I honestly don't know if my code is ANY more robust than if I had written it in JavaScript.
Record<> is broken/unsound: https://github.com/microsoft/TypeScript/issues/45335
Generics are wonky and sometimes wrong: https://github.com/microsoft/TypeScript/issues/31006
The `readonly` keyword does absolutely nothing: https://github.com/microsoft/TypeScript/issues/13347
Arrays are covariant in their type param, so I can pass a `Dog[]` into a function that accepts `Animal[]`. If that function adds a `Cat` to the passed array, the compiler is perfectly happy, but we'll see a runtime error.
TypeScript is actually so bad that it might have honestly made JavaScript worse, if that's even possible.
Calling it "broken" is complete hyperbole, and no, it's not "worse than Javascript". There's a reason why the entire ecosystem is switching to Typescript, and that's because it is extremely effective at helping teams manage complex stateful applications.
Its type system is quite broken and I'm not going to walk back on using that term. Sometimes the TypeScript designers/devs will explain that the brokenness is intentional. But some of the issues have nothing to do with JavaScript compatibility. For example, we all know about the conundrum of `type` vs `interface`, but did you know that an object-shaped `type` will automatically conform to a mapped type, but an `interface` wont? Playground: https://www.typescriptlang.org/play?ssl=20&ssc=1&pln=21&pc=1...
Or how about the fact that basic inheritance sub-typing doesn't work?: https://www.typescriptlang.org/play?#code/MYGwhgzhAECCB2BLAt...
Well, when comparing it with strongly typed languages it does look broken for sure.
The proof is in the pudding. I've been writing JS (and a bunch of statically typed languages) for over twenty years. Large JS codebases have become possible now thanks to TypeScript (an example is VSCode). If you look at any large JS ecosystem project today, chances are that it's written in TypeScript rather than in vanilla JS. People are adopting it because they see benefits.
If you've used TypeScript over the years, you'll also see that many major releases catch a set of new bugs in "strict" mode (which used to successfully compile earlier). That's the team fixing some of the issues you mentioned.
I understand the point. I just don't think it's a good point. If you tell me that I have a type system, then I'd expect that I could actually lean on it to catch type errors, and I'd expect it's own language features (like `readonly`) to actually do what they claim they do. I would NOT expect someone to add `readonly` to their language, but have it not actually make something a `readonly` type.
> The proof is in the pudding. I've been writing JS (and a bunch of statically typed languages) for over twenty years. Large JS codebases have become possible now thanks to TypeScript (an example is VSCode). If you look at any large JS ecosystem project today, chances are that it's written in TypeScript rather than in vanilla JS. People are adopting it because they see benefits.
I don't buy the argument that something being popular means it's actually good. There's a lot of group-think that goes into things being adopted. Not to mention that it's a Microsoft product and they have zillions of dollars to make sure the editor tools are good, lots of popular JS libraries get TypeScript types added on top, and just plain old PR advertising.
And yes, the ability to gradually switch from JS to TS makes TS an easier choice for people who are already working with JS or who are used to JS. But, that doesn't mean that Flow, Elm, ReasonML, ReScript, ClojureScript, PureScript, etc, aren't actually better tools with bigger benefits. It just means that TS got the critical mass mindshare amongst JS devs, and now has the advantage of "everyone else is writing libraries for TS, so if I pick Flow for my project, I won't have as big an ecosystem to pull from."
To me, each of your examples of brokenness is completely outside the day-to-day which I work in (and honestly my comprehension vis a vis why you would use them), so I can't speak too much to them, but as someone who has gone from untyped JS (obviously) to strictly typing each key of each property in my program, I am finding it pretty funny to see you conclude
> TypeScript is actually so bad that it might have honestly made JavaScript worse
I couldn't disagree more. The quality of the programming, the ability to share the mental model more easily with others, the developer experience of autocomplete and declaration files; each of these things is an order of magnitude improved, and the emergent efficiency of individuals and teams follows suit.
Well, I literally said that I shit on Java all the time, so yeah... I hate most of Java, and my blood pressure goes up just thinking about the shitty null handling, lack of any concept of immutability, weak as hell type system, and the nightmarish combination of commonplace runtime reflection paired with type-erased generics.
> To me, each of your examples of brokenness is completely outside the day-to-day which I work in (and honestly my comprehension vis a vis why you would use them), so I can't speak too much to them, but as someone who has gone from untyped JS (obviously) to strictly typing each key of each property in my program, I am finding it pretty funny to see you conclude
It's not outside my day-to-day. I'm complaining because I'm being bitten by TypeScript's brokenness all the time. If you try to use the advanced TypeScript features, you'll hit all manner of inconsistencies and brokenness, too. I'm sure of it. And if you're only using the very simple typing, are you really doing anything that JSDoc wouldn't do for you?
I'm fairly convinced (and I don't mean this in a condescending way) that the main group of devs that really likes TypeScript must have done mostly JavaScript and/or Python before. Because I can't imagine that someone who has spent a couple of years doing C# or C++ or Rust or Swift or even Go would be comfortable with all of the holes in TypeScript's type system.
The biggest holes can be filled via compiler options, and most of the rest can be papered over with the right coding practices (use Maps instead of Records, lint against `any` and type-casting, etc).
I haven't encountered the situation you described, but you could probably solve it by making the function generic over TArray extends Animal[].
The rest of what you've said doesn't line up with my experience. TypeScript is an imperfect tool that requires some elbow-grease to fully benefit from. I would prefer a typed language that didn't have to work under its real-world constraints (but not Java, because of null-checking at the very least), but over the years it's caught more bugs for me than I could possibly hope to count.
There's no earthly reason that a `type` should automatically implement Record<string, unknown> and an `interface` shouldn't. That's just dumb and annoying- not necessarily "wrong". However, it's definitely wrong to allow me to pass `const o = {}` into a function that wants `Record<string, string>`. How in the world does TypeScript (with the strict flag set!) think that an empty object is able to return a string value for any arbitrary string key? That's absurd.
The issue I raised about arrays isn't just arrays, actually. It happens with object fields as well. See https://www.typescriptlang.org/play?#code/MYGwhgzhAECCB2BLAt...
And, the `readonly` keyword has nothing at all to do with JavaScript. Yet, they added this keyword that is completely and utterly useless. To the point that I actually introduced a bug in my own code because I put `readonly` and `Readonly<>` everywhere and expected it to actually help me. It did help me... most of the time. And then it didn't. Because it turns out that you can always take a Readonly value, assign it to a non-Readonly variable and then just mutate the hell out of it, and the compiler won't even bat an eye: https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgA...
That's just... so bad. I don't even know what else to say. Sure, it caught some of my mistakes, but if it won't even catch all of the class of errors that it's supposed to, then I have to basically be just as careful as if I didn't use the feature at all. So, it's not reducing my mental burden at all. If anything, it's just giving us/me a false sense of security and tricking me into thinking that I DON'T need to be as careful.
The same is true for Java arrays. I thought the Liskov substitution principle was tautological when I first heard about it, but it seems like the original designers of Java disagree. Another example (albeit from the standart library, not the typesystem itself) is that if you try to modify a `List` or similar collection, it may throw an `UnsupportedOperationException` because it's immutable - instead of having a superinterface with only non-mutating methods and only implementing that.
First point: Yes, Java's arrays are broken and it offends me greatly. However, in practice, it's much more common to use Lists, which are not broken. In JavaScript/TypeScript "Array" is the equivalent of Java's List, so if you want a dynamically sized, contiguous, collection, you are stuck with the broken thing.
Then, the other issue is that, despite my comment's wording, this problem isn't ONLY present in Arrays. It's also a problem with objects, and (I assume) every other non-primitive type. See here: https://www.typescriptlang.org/play?#code/MYGwhgzhAECCB2BLAt...
So even a basic object field is broken in TypeScript's type system. What the hell are we supposed to do with this?
I do have thoughts and opinions about Java's Collection interfaces, the immutable implementations, etc, but that feels like a whole other topic.
This is an unfortunate relic of pre-1.5 Java. The rest of the Collection API types correctly. A type-safe generic alternative is Arrays::setAll.
> if you try to modify a `List` or similar collection, it may throw an `UnsupportedOperationException`
Again, an historical artifact. `List` is from Java 1.2, you would effectively have to deprecate List<T> for that to work.
However, a question:
> Arrays are covariant in their type param, so I can pass a `Dog[]` into a function that accepts `Animal[]`. If that function adds a `Cat` to the passed array, the compiler is perfectly happy, but we'll see a runtime error.
I don't think this one is true anymore, assuming you type it correctly. I've provided an example[1].
---
Separately however, I think it's worth noting that I've been playing with the idea of doing a project in plain Javascript again, to see if I feel any serious productivity losses.
- [1]: https://www.typescriptlang.org/play?#code/C4TwDgpgBAwghsKBeK...
You are correct that using a generic does fix the issue. But you called that "correct". But why, as a code author, should it be my responsibility to understand type theory better than my compiler? Because, according to basic type theory (to the extend that I understand it), TypeScript is allowing an operation that is literally incorrect in the first example. (mutable) Array types must be invariant in the type parameter. It should bitch at us for both examples.
And this won't happen with just arrays. It'll happen if you do the same thing with an object with a field. E.g., instead of `Animal[]`, we could have the function take a `{ pet: Animal }`, and pass it a `{ pet: Dog }`, and replace the Dog with a Cat, causing a runtime error for the poor schmoe who thought he still had a Dog.
You gave three examples that seem relatively rare. At work we use TypeScript to type a codebase that was mostly plain JavaScript, and we write TypeScript as plain JavaScript. It does very well its job of offering use better tooling and compile-time guarantees. If you consider it as a way to statically-type existing JS codebases, it's good. If you consider it as a language on its own, it's not great.
I gave a few more examples in other comments in this thread. I can go look at the code comments I wrote in my project and come up with a longer list for you if you like.
> You gave three examples that seem relatively rare. At work we use TypeScript to type a codebase that was mostly plain JavaScript, and we write TypeScript as plain JavaScript. It does very well its job of offering use better tooling and compile-time guarantees. If you consider it as a way to statically-type existing JS codebases, it's good. If you consider it as a language on its own, it's not great.
This is a legitimately genuine question: if you're treating TypeScript as just type annotations on an otherwise regular-old-JavaScript codebase, then why are you using TypeScript rather than just JavaScript with JSDoc comments?
Also, I can't quite tell. Are you defending TypeScript's brokenness by suggesting we just don't use all of its advertised features? Isn't that... kind of weak? It's like the joke about going to the doctor: "Doctor, my elbow hurts when I do this." "Well, don't do that!" -- If TypeScript advertises a feature, shouldn't that feature, like, actually work?
The problem is that function parameter variance is still wrong, even with all the strict flags. You just have to wrap the Dog/Animal in an Array or object. Pass in an { pet: Dog } to a function that accepts a { pet: Animal }, and the function can replace your Dog with a Cat, and TypeScript is perfectly happy to let you call `o.pet.bark()` afterwards.
Java has a much better standard library - abstract data type interfaces, common and fast data structures, I/O facilities, concurrency, and more.
[0] https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
There is a slight trick here, because this java interpreter uses a few special JIT optimizations, but it is still 100% java code (and the clever reuse of the engineering marvel what the JVM is). (Also, do check out the Graal project, its AOT compilation may be the least interesting part! It can even inline python code into js and optimize them together!)
Also, Java will soon get virtual threads that will automagically become non-blocking, even if they are written with blocking code (similarly to go). Currently in incubator mode is the Vector API which let’s people write really low level SIMD code that can cleverly query the processors capabilities and will even safely fallback to for loops on ineligible CPUs. FFI will greatly improve also with project Panama, so libs like tensorflow can get better integration into the JVM.
And last but not least, Valhalla is coming with value types. Yeah, it won’t happen for a few years still, but once it does, there will hardly be a platform as performant as the JVM. So, while we have heard it plenty of times how java will soon die, I think it’s future is brighter than ever.
Perhaps for some specific use cases, but certainly not for others. I also suspect moving from a fairly broad "stdlib" and somewhat curated 3rd party packages to the wild west of npm might be a barrier for many.
Javascript is singlethreaded
… which is why the root comment looks like pure trolling.The new cross-plat runtimes and languages we could have had by now if JavaScript didn't have a stranglehold on the available browser-side language space... wow.
Probably barely working, super fragmented garbage. A standard that isn't optimal but works well enough is fantasic in comparison to everybody trying to make their own thing. And realistically, if something else would have emerged, people would whine about it just as much as they do about JS.
Nowadays, we can use pretty much any language we want and compile it down to JS/WebASM. And most just add some compile checks with TypeScript. Because that's good enough, and it works.
Another way is to appreciate the fact that we have an open-platform with a standards body that actually works (queue the responses about how it actually _doesn't_ work). I can write an app once and access it from any device and it will work today, and it will work 10 years from now.
No other platform has achieved what the web browsers have, so I think we might be doing something right.
Pretty cool article. I've been dealing with JS for years without ever thinking too hard about how it all works
The hard truth is that Javascript does not actually achieve great performance. It's squarely in the back-middle of the pack. It's just that it's vastly improved versus its old self, and the methodology to get there has been wildly complex.
Of the languages tested in the alioth benchmark, more than half outperform node.
This should not be surprising, given its lack of basic containers and algorithms, and the inability to make the real thing. (No, an array containing an item and another array isn't a linked list. No, Okasaki containers aren't the real thing. Your complexity guarantees undermine your confident statements.)
https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
It might be close to as fast as it could given the inherent constraints of the language, but I would not call it fast in a general way.
[0]: https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
You can do that in node too via NAPI or you could compile to wasm and run there instead.