336 points · by okket · 8y ago · 233 comments
What if there is a bug (or even a misconfiguration in your project)? Or typescript changes over time (and now there are different versions all needed to be supported)? Or what if the types from typescript (designed for programmers) are not always inline with V8 internal representation of objects?) Or what if people push typescript through V8 with compile time errors? (The compiler should have prevented this from happening - but you can pump whatever you want into V8, including things considered broken by typescript).
You only really get any improvement in runtime if your compiler guarantees anything (and bakes it into whatever it is compiling). As of now there are little guarantees with the javascript language (which is what comes out of your typescript compiler). AFAIK typescript is designed to help programmers find common bugs.
Not saying it's not possible, but more work is needed into bridging the two.
Not only that but you can expect to get better performance from the JIT than AOT because the JIT can perform optimisations which are impossible for the compiler.
And you are likely to be disappointed. I think these claims have been made for the last 20 years, and Graal might be the first to deliver something general - all previous successes were very limited to small niches.
I like JITs and what they offer, but very consistently for me and almost everyone I know, in practice AOT works better (faster, consistent, no "heuristic changed in JIT version and now it's slow" surprises).
I can’t help myself, but the JVM performs at par with managed AOT languages (Go, Haskell, OCaml, etc) and strictly slower than the unmanaged AOT languages (C, C++, Rust). The JVM does outperform various AOT Java compilers, but that’s probably an artifact of the decades of optimizations that went into the JVM; the same investment in an AOT compiler would close the gap to within the margin of error. Anyway, sorry for my compulsive nitpicking; hopefully it was interesting.
Is there an example of at least one such optimization? As JIT is not magic, it also compiles things ahead of time, but a little bit ahead of time and it is very constrained on how much time and resources it can waste. It also can't afford to slow down interpreter too much, can't do excessive profiling, can't do big changes to the code that touch half of all the functions and data structures for example, etc. While AOT can do that and I can't think of anything JIT does that AOT can't do.
> You only really get any improvement in runtime if your compiler guarantees anything (and bakes it into whatever it is compiling).
I meant this in reference to runtime speed optimisations coming from types. V8 is improving every day!
I'd say it would be a lot easier to simply focus on the WebAssembly format, you can write your code in a number of (typed) languages and compile into wasm which is designed to be fast.
Javascript already comes with a few decades of bagage, and things are already changing really fast (ES6 and newer versions). Not everyone likes types and the people who do can use typescript (or flow). And the people who need insane performance (games, etc) can use WebAssembly.
It would definitely help moving sections of the code up the tier ladder, not unlike Web Assembly.
I even predict that future typescript versions would include stricter typings optimized for an browser to solve problems like others have mentioned in the thread.
Or just a TypeScript engine in the browser, like ehm Dartium. I guess someone at Microsoft already did this on IE in a hackathon or something.
Even if we consider that good enough or somehow solved, understanding type annotations only helps you reaching peak performance faster. It doesn't really make peak performance faster.
Also there are the PyPy and Dart devs that in theory could use type annotations, but both don't. For PyPy they even have an entry in the FAQ: http://doc.pypy.org/en/latest/faq.html#would-type-annotation...
I don't really know about the details fo Pypy, but from what I gathered from performance talks about V8 between the hidden classes and inline caching it would strongly benefit from these behavioural changes.
Basically, it doesn't preclude the runtime from having to do its analysis, but it makes the analysis & optimisations "hit" at higher rates than they would otherwise do.
Do you? I remember reading that LJ is able to infer ints for e.g. loops with no specific effort (neither performance hit).
Of course it will take a while to be supported everywhere, but they are taking steps in that direction at least.
As a ruby developer, I'm insanely jealous.
This keeps me happily in Rubyland.
One bad default setting and [0]BOOM! [0]https://github.com/rails/rails/commit/b83965785db1eec019edf1...
Amusingly given all the PHP hate, if you want a faster rails-like framework, Laravel might be your best bet.
To which I agree with the Express / Sinatra similarity.
Sails -> Rails
As an Internet user whos has been reading for years about how fast the various js engines are it annoys me that the web still feels slow :-]
Your comment is also borderline rude, as it implies that anyone using JavaScript are unfortunate. I mean, what did you really want to achieve by posting that comment?
There’s definitely room for improvement, and the inclusion of JIT infrastructure is awesome, it’s just not making much of a performance impact. Yet.
However it doesn't necessarily cause a large slowdown, just makes your function polymorphic and the resulting optimized code larger and a bit slower.
To avoid this entirely I recommend using a JavaScript `class` when passing objects to a function that has to run at peak speed.
function vec3 (x, y, z) { return {x, y, z} }They could change the representation to not be insertion order dependent, and store insertion order in a separate data structure, but that has its own trade-offs.
The "new" generation of JS VMs (V8, Chakra, Carakan) all dropped insertion order for array index properties (that is properties whose name is a uint32), but kept it for everything else; that broke about as much as browsers are willing to break, and breaking the general case would be far, far worse.
It's complicated. The spec says order of for..in is not defined, browsers all implement the same order, and there keep being attempts to get the spec changed to match.
Object.keys, however _does_ have a defined order. https://tc39.github.io/ecma262/#sec-object.keys calls https://tc39.github.io/ecma262/#sec-enumerableownpropertynam... which calls the [[OwnPropertyKeys]] internal method. For normal objects this is defined at https://tc39.github.io/ecma262/#sec-ordinary-object-internal... which calls https://tc39.github.io/ecma262/#sec-ordinaryownpropertykeys which completely specifies the order: integer indices in ascending numeric order, then other string-named props in order of property creation, then symbol-named props.
This is pretty blatantly incorrect. Just because a problem is undecidable in general doesn't mean that there aren't specific cases where it can be solved. Optimizing compilers deal with undecidable problems all over the place, generally by either being conservative and lumping together proved-impossible with unable-to-be-proved invariants, or doing speculative optimizations with an unoptimized fallback. Just proving the type of a variable in Javascript is undecidable in the general case
My hypothesis (as someone who used to work on a JS VM) would be that locations of iterations over an object's keys and the creation of the object are almost always in different functions, with the object passed between them. And note that JS VMs rarely do cross-function optimization. As such, it would be exceptionally rare for the optimization to be applied.
My point was really that you can't always drop the ordering of properties, and the insertion order isn't something you can recreate after the time if you don't store in initially, hence you do really need to store it somehow.
(If anyone's confused, I edited the grandparent comment of this to better reflect the above.)
but how do you know it's wrong (if the iteration order of a .keys() call isnt the same)?
Unless you forbid any impure operations you can't just deoptimise and re-execute code to then store the ordering. (I'm sure this isn't what you meant, and I'm probably being silly!)
https://richardartoul.github.io/jekyll/update/2015/04/26/hid...
Maybe I'm tainted from my experience building / debugging J9 / OpenJ9 but... Why is this considered extreme? If one strays one iota from the standard platform ABI, which is basically a necessity for producing a performant runtime (PICs being an easy example), this is where one ends up.
Sure, you won't beat C for low memory devices or hardware that you have complete control over but for 90% of use cases javascript actually makes sense and can be the most performant.
Thanks to V8 you can definitely achieve good enough performance with JavaScript for most applications, and the ergonomics are pretty great. But it’s not true that performance rivals or beats C in the general case. The ‘sufficiently advanced compiler’ rainbow is something that Java has spent decades chasing. I think it’s fair to say at this point that humans are better at writing C code than we are at writing clever compilers.
It’s many of the exact ergonomics which make JavaScript useful and easy to use that also make it much harder to optimise. For example, what code should V8 generate for `x+=x` ? The optimiser might find that x is always a positive integer, but every time it gets doubled, it might cross the magic overflow point where it needs it’s representation swapped for a double. The generated code must check for this every time. Or consider memory management - For games I’ve heard of people making a per-frame arena allocation pools for values with a lifetime that won’t cross frame boundaries. This basically makes these allocations free and improves cache coherency. I’m happy that the JS GC is multithreaded now, but there’s no way a GC can compete with that. And unlike C, there’s no way in JS to override the allocation behaviour.
There are a million paper cuts like this which lower the ceiling of how fast optimised JS can run. I’m glad V8 will keep improving, but for my money the future of really fast JavaScript is Webassembly.
Games are a special case where each ms counts. Globally, the number of LOC written for consumer or business software dwarfs that of game code and for these kinds of applications JS is well within the realm of performant enough. That assumes you're not doing your presentation layer using the DOM though which is still garbage wrt performance. Luckily there are things like Qt to make high performance UIs in though.
>> Thanks to V8 you can definitely achieve good enough performance with JavaScript for most applications
The point I argued above isn’t that JS is slow. It’s that JS will probably always be slower than well written C code. I still write far more JS than C, because my time is usually more valuable than the computer’s.
That said, games are far from the only place where every ms counts. Performance matters in database servers, operating systems, real-time applications (eg robotics), text editor typing latency, UI responsiveness, 3d modelling software, video encoding, cryptocurrency mining, browser DOM rendering and so on.
I love JS, but native code is not a special case. Despite the best efforts of Electron, I suspect most of the globe’s aggregate clock cycles are spent running code written in languages other than JavaScript.
I wonder if compiler hints can help in that regard? For example, if performance is important then you could annotate the 'x+=x' line to tell the compiler to not check for overflow.
There will always be some cost here, because at runtime you need to check if your assumptions still hold. Some of the time you can pull these checks out of loops, but sometimes you can't, and they can be costly.
There are a few things a JIT can theoretically do better. Inlining is the biggest one. For example, a JIT knows not to inline a function that never gets called, and it can also do inlining for indirect calls based on profile data. A JIT could also theoretically move unexecuted blocks out of line for better instruction cache locality. It could also check for aliasing at run time (with a bailout) and then optimize a loop assuming no aliasing.
Unfortunately for JITs, AOT compilers can do a pretty good simulation of most of these things with PGO, that is running a scenario with an instrumented binary and re-optimizing using profile data.
Still can't bailout if an assumption is wrong, so it doesn't work for dynamic languages, but you don't really need bailout for much in static languages.
However, those isolated examples rarely if ever translated to high performance in real-world projects. The same issue has an experience report of the travails of IBM's San Francisco project. Performance was a huge issue that to the best of my knowledge they never fully resolved.
More in my article "Jitterdämmerung": http://blog.metaobject.com/2015/10/jitterdammerung.html
So he debugged some more and figured out that he misunderstood some of the inner workings of how vectors copy data and also that he did not understand the threading library he was using properly. He then fixed those two things. After this further exercise he reduced the difference to factor of 4. However he was never able to work out why my code was 4 times as fast as his C++ and abandoned it.
I know for sure that with appropriate expertise the C++ could probably be made to go perhaps twice as fast as my Groovy code. But the point is, none of the supposed benefits come automatically regardless what language you are using. And unless you flip over to GPU or FPGA accelerated methods, the final outcome is well and truly in the same ballpark anyway.
But all this is to say that "rarely translated" might be true at the for applications that are completely in the high performance domain. But for all the applications where the high performance code is in niches at the edge and there simply aren't resources or expertise to fully tune the native implementation ... I think it's translated all the time.
Then I moved to Google, working on the indexing system and properly learned C++. I've since worked on several projects for several companies where the annual cost for compute time is easily 200 times my salary. These are systems where it pays to extensively profile both CPU and I/O and retain C++ optimization experts.
I still see the appeal of platform-independent binaries and dynamic optimization, but you really need the startup time and optimization cost advantages of ahead-of-time compilation. Hopefully the platform independence and dynamic optimization features would also be decoupled from the garbage collector.
HP Research had project dynamo that was basically a tracing JIT emulator for PARisc CPUs that ran on PARisc. It showed that binaries compiled with -O2 could get performace comparable to -O4 through dynamic recompilation.
Ideally, we'd distribute programs in a compact and compressed CPU-independent SSA representation similar to SafeTSA or LLVM bitcode. Installation would AoT-compile the binaries and keep around the SSA form for use by an HP Dynamo-like runtime optimizer. The AoT could compile functions and methods to lists strait-line extended basic blocks with a call to a trampoline loop or other techniques for lightweight instrumentation/tracing of native code. The dynamic optimizer wouldn't need to work with arbitrary machine code, only AoT compiler output. Also, it would never have to disassemble native code, but could always start by gluing together the SSA for each extended basic block in the trace.
A few CPU features could make native tracing and dynamic recompilation extremely light weight. Unfortunately, Intel and ARM are disincentivised to do so, as it would make it easier to migrate off of their intellectual property.
Edge cases. But obviously it's not comparable to something ahead-of-time compiled and hand profiled with PGO and stuff. Although in theory you could put that through JIT too, but it would probably just add overhead and only slow things down.
Pretty cool that it can run faster than AOT compiled C, any benchmarks or posts with more details on this?
They found that most programs ran slightly faster in the JIT. I'm still not sure why this technique didn't catch on.
which is what java touts as being able to do. Unfortunately, i think this sort of speedup is really dependent on the application (and the developer using common idioms that is recognized by the JIT).
You could make a JIT language as fast as C so long as it supported value types properly. Most programs in the "slow" languages spend most of their time chasing pointers around.
I think JS is now within a factor of five of C, but JS programmers are significantly more blase about performance. In many cases they won't blink at a quadratic algorithm when a linear or nlogn one is possible, provided the quadratic algorithm is cleaner.
Ditto constant factors -- a C programmer might go out of their way to not iterate over a string more times than necessary, and a JS programmer won't. A C++ programmer might try to minimise lookups into a map, and a JS programmer won't. Some JS shops strongly encourage `array.forEach`, which is 6-7 times slower (on my machine) than an "old-school" `for()` loop.
For most web apps it makes no difference, but if performance ever does become a problem it can make it harder to fix. In my experience, profiles in "fast" languages in codebases written in the traditional paranoid style tend to be "lumpier" than profiles in "slow" languages written in the fashionable cavalier mode.
None of this is to judge anyone. I think being lazy and implementing an O(n^2) algorithm is perfectly reasonable when you know n is always going to be small, but I am cautious -- as much as the increased productivity is fun and addictive (and real in my day-to-day work), I've also seen the death by a thousand cuts first hand.
I'm sure Python, Ruby and PHP would benefit just as much from such attention, although I guess Python has had that in scientific computing, and PHP with recent 7 version and FB.
Not much respect, but more acceptance as a unavoidable language to use that thanks of millons of $$$$/human-hours of effort to polish it... is ok-ish.
You can argue whether everything moving to web apps (and I may be using the term web apps wrong, but I’m speaking about anything that runs in a browser) is such a good idea, it’s probably not, but it’s whats happening because it’s really fucking awesome in terms of getting things to actually work across multiple devices.
JS does something none of the other tech stacks does, in that it integrates really well with your current stack. I work in enterprise, we operate more than 500 different it systems, and most of them run on windows. So natural,y our operations ninjas are really great at Microsoft tech. Operating ruby, PHP, python and so on can certainly be done within the windows environment, but we’ve naturally been doing .net since it fits in better.
JS fits into this infrastructure perfectly. A lot of it is thanks to MS, but we haven’t had to spend money on retraining staff to integrate modern JS into our stack.
The language itself offers a lot of freedom, which includes risk, but I don’t personally think it’s worsening that regard than python.
This is how people end up using it on the back-end when they do have a choice.
Though "respect" is a corny word to use for any language. I don't respect my screwdriver either.
It's not that performant either, it's just that it's getting closer to Java-class performance which is enough for many types of workloads.
JS is living proof that throwing enough money at a problem can go quite a long way.
You can't just take advantage of SIMD, hyperthreading, multicore, or large caches without writing code in a way that takes advantage of that even at a high level. Some things can be faster when compiled at runtime but everything is a trade off.
But ultimately I believe that C is fast mostly due to manual memory management but that's not a trade-off I'd take for most tasks.
v8 is an amazing piece of engineering but it's not at the point where it allows application developers to take much advantage of SIMD, hyperthreading, or multicore.
I think he means this is done behind the scenes without your knowledge (some compiler/runtime magic), not some interface you can take advantage of.
Automagically parallelizing general serial code is something that isn't feasible on any hardware similar to modern cpus and probably will never mesh well with fast single-threaded performance (communication and synchronization in hardware is HARD)
But it gets even crazier. (Non-Smalltalk) In the 90's, there was an OS entirely written in a virtual Instruction Set (TAOS) which was JIT assembled into real machine code as fast as it could be read off of disk and ran at 80-90% of native speeds. This OS could be ported by simply porting the assembler, which typically took about 3 days.
Back to Smalltalk craziness. There were also in-house research versions of Smalltalk that could prune their images as small as 45k, and were suitable for creating command line tool executables. As it was, VisualWorks, if you turned off things like the splash screen, actually could start faster than the Perl runtime in the late 90's, though you'd be hard pressed to create an image below 500kB. (Even getting it below a megabyte was an incredible feat.)
The tech industry could be way ahead of where it is now, if only everyone were like early adopters. The thing is, most people are quite different.
As you say, I really wish tech had followed that route, think of all the cool things we'd have.
http://www.modulaware.com/mdlt69.htm
It's one of those alternate histories for Web development I wish took off.
But it's not c level performance. Throwing multiple cores at js to get c level performance glossession over an important detail: in C, those cores are free to do other things.
This is a weird definition of performant, using more resources to achieve the same result faster, it seems akin to saying JS is more performant than C if you buy a newer CPU to run the code on.
> But the more I've learnt about the benefits of "on the fly" / "just in time" optimising compilers, the more I'm convinced this is the future of computing
It's been the future of computing for 30 years, possibly longer.
You can write a multi-threaded optimizer that works on single-threaded code. Using multiple threads on multiple cores to optimize single-threaded code ... is pretty darn cool, but barbegal never said it made the single- into multi- ...
You can't with Javascript. You need concurrency-friendly programming model and code structure for compiler to be able to do anything that fancy.
If you’re asking why PHP hasn’t died...Well, because it’s still useful. In the real world you don’t change your tech just because something better comes along because it’s tremendously expensive to do so.
That’s why cobol is still around, and if you want an example of something even worse, it’s also why you still find companies using classic ASP and so on.
And PHP isn’t really that bad. Parable is tremendously productive.
So it's fast these days... great? There's more that I seek for in a language than just speed. PHP7 and Pypy also do a pretty good job, and one can always offload the heavy lifting to some compiled code if it's really that important to squeeze the last few percent of performance out.
The only thing unique to JS (afaik) that I really like is addressing dictionary keys as object properties (`a={'test':512}; console.log(a.test);` instead of having to do `console.log(a['test']);`). I'm not sure why that is so oddly satisfying, but it is.
That's floating point math, and persists in many languages [1].
> Variable definitions are global scoped by default, semicolons can randomly be omitted, etc.
Nothing random about it, automatic semicolon insertion is well defined/documented [2]. Also let [3] is your scoping friend.
[1] https://0.30000000000000004.com/
[2] https://www.ecma-international.org/ecma-262/7.0/index.html#s...
[3] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
Figured someone would say that. Yes, of course it's not random: it's a computer, it follows the same instructions every time.
What I meant, of course, is that it isn't logical. You can't guess it without having to check the spec. In bash you know that a newline is as good as a semicolon, in C you know you always need a semicolon, and in Python you know you never need it. In JS it's somewhere in between. Reading that spec, it's when the next line would have syntax that is illegal if it were a continuation... so you have to do JS simulation in your head to check if your code could, perhaps, make sense as a line continuation. So I guess you just always have to do it. I'm not saying it's a major issue and this is the one reason I don't use it, but similar to how people criticize PHP for having inconsistent function names (which is also not a bug or broken), it would have been nice if it weren't the case.
> let [3] is your scoping friend
It's not about it being possible, it's that global scoped default is just asking for abuse of the global scope. Even PHP doesn't do that, and PHP is really made for quick and dirty web development (or at least it used to be, so it supports many things that make that possible).
The functional stuff was weird for a while but just keeps growing on me.
In addition, while you'd have a hard time paying me to code PHP, a huge percentage of PHP devs like the language.
Of course, because you don't write a web server in PHP. You put it behind nginx or apache and those can fork off PHP processes (or you use FPM, or etc.) to do everything for you.