481 points · by fabian2k · 3y ago · 188 comments
Super wasteful when you start thinking about what all that means. Rather then having a representation that neatly fits into registers, now you have this blob of memory that has to be linearly searched to pull information from it. Just. yuck.
And why do devs do this? TBH, I really don't know. Because regexes are easier to understand? IDK.
it's one of the pillars of the unix philosophy at work - text is the universal interface.
your nice rich type requires figuring out how that type works, maybe even reading documentation. if you make it a string, you can just treat it like a string. and we all know how to handle strings, or at least how to copy code from somewhere else that handles strings.
I'd also caution that "everything is a string so no need to read the documentation" is unrealistic and even outright dangerous. *NIX's string philosophy has directly resulted in multiple security vulnerabilities.
i figured the article we're all commenting on would be evidence enough of why it's not necessarily a good idea.
For example, in a library one of my coworkers wrote, object paths were flattened into strings (eg “user.address.city) and then regular expressions and things worked on that. Sometimes user data ended up in the path (eg “cookies.<uuid>”). But then - what happens if the user puts a dot in their cookie? Or a newline? Does the program crash? Are there security implications we aren’t seeing? What do we do if dots are meaningful? Do we filter them out? Error? Escape them (and add a flurry of unit tests?) Are there bugs in the regex if a path segment is an empty string?
It’s a nightmare. Much better to have paths be a list of keys (eg [“cookies”, uuid]). That’s what they represent anyway, and the code will be faster, and this whole class of string parsing bugs disappears.
Perfect is the enemy of good though, and probably 90% of my code is done properly, and I cut corners where I think it's appropriate - sometimes thats ok, and sometimes in hindsight it's not.
Not a statement I ever expected to see.
One time, to solve the problem of "we want floating point numbers that are close to be considered equal" on an object, the programmer decided to take every field of that object (reflectively of course) turn that into a string, and then compare the two strings together.
Another time, in order to convert a LocalDate to our own internal date representation, a dev decided to toString the local date, split on the `-`s to extract the day month year. (Yes, localdate has day, month, year methods).
One time, to convert an int to a double a dev decided to turn that int into a string and then used "Double.parseDouble" to turn that int into a double (I wish I were joking).
All these and more were found through the joys of profiling :D
I once didn’t want to write or add a dependency for a Python deep equality checker so I just sorted, JSONified, and string compared the two. It worked fine for years. It wasn’t performant important code.
But it still keeps me up at night.
They also did that exact same thing parsing dates, except that they flubbed the logic and IIRC had an off-by-one on the month for the constructed Date object.
I have seen this kind of code many years ago when external company was brought to sell us their implementation of CMS on some (even then) outdated Java/js-on-server-before-node-era platform. I was asked to do code review to chcek if their code can be integrated into our codebase.
I was quite unexperienced at that point in time but enough so to notice that there was something off with the code. There was a lot js that looked almost like exercise in obfuscation. Things like doing join, append and split on array to do push - and it was not abstracted into function - this three operations were repeated all over the code. And then I met the programmer - it was ovious after few questions that he did not know what he was doing and his direct manager, who was also present, know nothing about programming (he was more od a business person as he himself proclaimed).
It was as if this company hired the cheapes guy they could find, that on paper looked competent, give him task of implementing CMS, and only looked at results (the CMS actually worked), but no one ever checked the code that was hiding under (and the guy never worked with anyone else and never read any other code besides his!)
It made no sense.
But we were also in a rush to get this app built, so we didn’t push back on this tortured logic. But we were saddled with this technical debt for an embarrassingly long time.
Completely fails for a number big enough to be stringified to 1.34e20.
Plot twist, if your number is in a reasonable range this is very fast because there was one a popularJS benchmark that did this.
They find the strongly typed system "inflexible", so they fall back to a "stringly typed" one.
You don’t even have to know what the type is of the thing to work on it’s string representation.
Now imagine a bit of reflection on that to do some string manipulation.
Good times!
In c#, I would use a Tuple. Or override equals to do a deep check.
Strings seem really easy for composite keys and "deep comparison" for objects, but you could do more like C# actually does under the hood which is compute simple hash numbers (getting back to the article's point that computers are often faster with number calculations than string work).
C# does most of its equality "magic" with GetHashCode() (surprisingly not Equals() and obviously not ToString()). (Relatedly this is why C# linters will yell at you if you override Equals but not also GetHashCode. Equals seems the more "useful" override but GetHashCode is the actual work horse.) Most implementations of GetHashCode (even for deep comparison situations) are generally starting with some random prime constant XOR bits of all the data and return the integer you have left after all the XORs. You can do the same thing in JS today if you wish. Modern .NET now has a nice System.HashCode helper class for doing it quickly with a lot of good best practices baked in (a strong starting constant, for instance), so it's easy to forget the bad old days of writing all those XORs by hand, and .NET has always had GetHashCode a required method of System.Object so "recursion" of hashcodes is guaranteed to be simple. But those things aside, it's still really easy to compute hash codes by hand in JS to use for comparisons than to use string manipulation, if you put your mind to it.
Postcss is not necessary for custom properties. IE isn’t a thing anymore, and using css custom properties directly without a transpilation step is fine. The same thing applies to the for … of issue. Babel is not necessary anymore, all browsers support ES8. JSX is the only thing babel still does that offers real value, but that can be replaced by the runtime alternative developit/htm. We can just stop using babel and sidestep this whole issue.
I see a lot of energy going into making faster build tools, and I feel this energy is misdirected. We need to dramatically strip down the build tools as most of them have become largely redundant since the death of IE.
Safari is fairly conservative in de-prefixing new features, but also sometimes beats Firefox (e.g. Container Queries and Container Query Units).
For reference, here's the caniuse.com list of Safari CSS features which need prefixing, compared to Firefox: https://caniuse.com/?compare=safari+16.1,firefox+107,ios_saf...
In the link posted by the sibling commenter, I see 2-3 properties that could be useful to the general public. The rest is esoteric, never-ratified, or straight up user hostile (font-smooth)
Mozilla/5.0 (Linux; Android 12; Pixel 6 Build/SD1A.210817.023; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/94.0.4606.71 Mobile Safari/537.36
Devs were NOT supposed to use prefixes in production, but they did anyway (best viewed in Chrome). Unfortunately they then proceeded to NEVER UPDATE these as other browsers added support. Non-webkit browsers had the choice of interpreting the CSS or leaving their users with a broken experience.
Major browsers moved away from vendor prefixes between 2012 and 2016 (when webkit finally stopped), but it was too late. Browsers 50 years from now will still be supporting this garbage because of what devs did.
The key takeaway: Never give devs a tool you don't want to be stuck with forever. Also, can we please not do this yet again in the future?
I don't know if anybody really does other directions of that, though. There was probably no percentage in working with -moz prefixes for other browsers by the time this became an idea to do.
You still need babel, tsc, or swc to transform typescript to JS.
And then there are imports of files that aren't JS (images, fonts, stylesheets, etc).
Typescript is indeed a given. There's no good way to do that without build tools. The question is whether typescript's benefits are worth the overhead of the build tooling. I tend to prefer it for libraries with strict API's, but I don't experience as much of a benefit for web applications. I think libraries also benefit a lot from bundling/minifying, so there I would choose a full build tools approach. For small web applications the overhead of the build tooling is not worth the benefit IMHO.
And then when it comes to direct imports of images, fonts, svg, I don't think people should do that at all, even when using heavy build tools. YMMV.
This will lead to slower FCP etc times particularly if the stylesheets aren't in cache
:(
what if we standardize browsers ? Like if it happens, we get easily all of the power from browser itself. It's same story like ES6 and later versions did to underscore and lodash (long live lodash).
This will make all build tools OBSOLETE
The Babel example problem in the article is a fascinating one because that's someone's metaprogramming that's just lost in the ether of time and the labyrinthine tower of a Babel install someone's too afraid to break to just tear down. Not only is it an unnecessary downlevel transform in 2022, but it doesn't look like any of the official transforms that common Babel transforms produced, so who knows what metaprogramming thought might be a good idea that delivers that from that configured stack?
As others have pointed out: JSX transforms have non-Babel options (also including Vite, esbuild, and Typescript).
As for other metaprogramming commonly done in Babel: I would point out that the Stage 0 Decorators that Angular was built on (not to be confused with the Stage 3 Decorators that might actually come to JS) have relied on very specific Typescript build options anyway and the double-up that Angulars tools by default do of also feeding that Babel is kind of silly.
One of those parentheticals also slightly buries the lede that there is a Decorators proposal at Stage 3 and likely to get added to Browsers "in the near future" for those that desperately want to do metaprogramming in JS to have metaprogramming in JS proper, no Babel needed. (There are Stage 1 proposals to offer even more meta- and reflection tools beyond that directly in the language.)
In 2022 though, it is worth asking what in JS needs metaprogramming? A lot of applications get by without it just fine.
How would I add syntactically nice things to JS?
How would I get my environment variable values set for the build into the code, which is to be run in a browser?
JS being JS, there seem to be no good facilities in the language itself to do that inside the language. My understanding is, that babel was created to do these things outside of the running script. Maybe there is another way that I am not aware of?
const swcOptions = require('next/dist/build/swc/options')
const { getLoaderSWCOptions } = swcOptions
swcOptions.getLoaderSWCOptions = function (...args) {
const result = getLoaderSWCOptions(...args)
result.jsc.target = 'es2022'
return result
}
This overrides the target https://swc.rs/ uses from the default of es5 to es2022, which sped up our quite heavy app by up to 3X in hot code paths, just by using newer JS syntax instead of falling back to 'transpiled' versions. Unfortunately Next.JS doesn't allow setting the target directly. My hunch is that especially this syntax in our hot path was a big benefactor: function cloneAndSetProperty(obj, prop, value) {
return { ...obj, [prop]: value }
} function chainedPrototypePlusProperty(obj, prop, value) {
const newObject = Object.create(obj);
newObject[prop] = value;
return newObject;
// Alternatively: return Object.create(obj, { [prop]: { configurable: true, enumerable: true, value } });
}
It depends entirely on what you’re doing with it (not mutating obj while you keep the returned object, not depending on properties being own), but in some cases this will be suitable, and depending on the data and what you’re doing, could be drastically faster (it’s O(1) rather than O(n) on the number of properties, and access after could be much of a muchness).True, optimize code for JS engines is certainly an art form of its own. What usually works for me is to write boring imperative code when performance is a requirement. That seems to be easily optimizable by current engines.
Also, thanks for sharing my article here on HN. First time for me one of them is on HN.
It's not that hard to guess. Just look at what most NPM/Electron programmers and guides recommend you do, and then do the opposite. I.e., think about what your program is doing, and write the most boring, 90s-style code you can. Works really well internally for the Firefox codebase, and has been for 20+ years (for longer than it has even been called "Firefox").
Relevant talk: <https://www.youtube.com/watch?v=p-iiEDtpy6I>
Relevant paper: <https://users.dcc.uchile.cl/~rrobbes/p/EMSE-features.pdf>
Relevant thread: <https://news.ycombinator.com/item?id=33790568>
* Objects should have a fixed set of keys (no adding more and especially no `delete`) and the type of the value should never change (note: in JS, a type must NOT be a union of multiple types if you want it to optimize)
* Arrays must be of one type and a fixed length
* Functions must take a fixed number of arguments and the type of those arguments must never change. This is by far the most important if you want to get your function's code optimized.
And as a corollary from this article, it's not JS specific, but converting string -> float and float -> string isn't a cheap operation. I'd go so far as to say that it is the most expensive operation in a huge amount of the functions where it happens. Int to string is especially egregious because it requires a lot of division which is basically the slowest (common) thing you can do on a CPU.
Yeah. There's some great benchmarking and tips: https://www.zverovich.net/2013/09/07/integer-to-string-conve...
Godbolt example: https://godbolt.org/z/M4b353PKv of which the meat is
imul rcx, rcx, 1374389535
shr rcx, 37
imul edi, ecx, 100
mov r8d, edx
sub r8d, edi
movzx edi, WORD PTR .LC2[r8+r8]
mov WORD PTR [rsi], di
So if our example input is 12345, the first two instructions use the field-inverse property to compute "123" with multiply rather than divide (1 clock, latency 4), then multiply up again to get "12300", then subtract that to get "45". That can then be looked up at position 45+45 in the string "00010203040506070809101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899" to give you the two digits.Declared in a fixed order if you want functions to remain monomorphic! One case where using classes is a bit safer than object literals.
If performance is critical then use a TypedArray where possible.
Your other points are spot on for high performance JS.
Does that mean that tagged unions (functional programming-style data types) are inherently slow in JavaScript? Maybe there is a way for the TypeScript compiler to pass pragmas (via comments in generated code) to the interpreter.
I think this advice goes way back to before the 90s. I've also heard it called FIAL (Fortran In Any Language).
But, yeah. It's basically always the fastest thing possible in anything even approaching the mainstream.
Viewed in those terms, it shouldn't be surprising that JS can be incredibly fast (faster than C in some cases).
Compared to what? Polar bears?
Here: is it faster than warm JVM?
You can't even store more than 14m or so keys in a map in Node w/o reaching for an off heap solution due to hard limits in the runtime...
// Does the same as `Number.prototype.toFixed` but without casting
// the return value to a string.
function toFixed(num, precision) {
const pow = 10 ** precision;
return Math.round(num * pow) / pow;
}
I know doubles are big, but doesn't this combination of multiply-and-divide introduce the possibility of precision issues that I'm assuming is not applicable to `toFixed`?Unless I'm wrong, I would be very hesitant to use this version of the method when I don't control the input.
toFixed(1000.005, 2); // returns 1000.01
toFixed(1.005, 2) // returns 1
Rounding to a fixed number of fraction decimals is extremely tricky, much trickier than it appears on first view.This is beaten to death at Stackoverflow, but I can tell you that almost all (or all?) of the solutions provided don't work for all cases:
https://stackoverflow.com/questions/11832914/how-to-round-to...
Many years ago (Adobe SVG Viewer days) my Dad generated SVG files from geo/map data and at first used the original coordinates or something, but float error made it untenable—some viewers would end up quantising some things (e.g. the shape, the viewbox, individual nodes, even once you applied a transform or SMIL animation to them, the hover hitboxes—I don’t remember the particular details, but it was a few things) so they’d end up off by as much as hundreds of pixels in the most extreme projections. Therefore he ended up rezeroing to work around this, transforming into a more friendly space before producing the file.
In the context of SVGO: really, the whole decimal places thing is stupidly bad, because decimal places can be of wildly differing importance in different contexts, and it wouldn’t be that hard to figure most of them out. In some situations a third decimal place will be more valuable than another number’s hundreds place. And SVGO’s approach is particularly bad because it treats each number individually, not attempting to compensate for the error it introduces, and so the presence of fine detail can easily completely destroy things due to untreated cumulative error.
BTW if one needs to round to more than 16 you can use toLocaleString and pass minimum and maximum fraction digits which has a limit of 20. Ain't much but you could not expect more from JS :D
Yeah, that was surprising to me too. You always discover something you would have never thought of on your own. It's what makes profiling such an enjoyable task for me!
Because most JS developers simply aren't your old guard neckbeard coders with decades of experience under their belt. They're fresh coding academy graduates that don't teach stuff like flame graphs or performance tracing in general, and simply are used to stuff taking a lot of time. And fwiw, knowledge of optimization techniques isn't really widespread even in senior developers. Modern computers are simply "fast enough" for many people (and especially corporate beancounters) to not care.
Nobody makes money from making SVGO faster.
Your customers don't run SVGO and only care about the performance of the output. Devs care, but not enough to do anything about it. Companies care about dev productivity, but the cost of the hours to run through the profiler isn't something they are willing to pay for.
And finally, there aren't enough maintainers/contributors to these projects. The core team is some volunteers. When they have spare time for the project, it's almost always going to be used to keep up with web standards, add missing features, or chase down bugs that impact the final output. They know performance matters, but thers's always something more important to do instead.
Can you elaborate on how you did the profiling to identify the (potentially) slow parts?
I mainly used node's `--cpu-prof` flag to generate a profile. Tried loading the trace into Chrome DevTools at first, but wasn't able to load the file supposedly because they are too big. So I used https://www.speedscope.app/ instead and which loaded them without any issues and is very snappy overall. What's more is that it allows you to display a left-heavy flamegraph which makes it much easier to spot functions taking up a lot of time. Speedscope is an amazing tool!
For webpack based projects the traces were missing quite a bit of data and I had more luck with their own profiling plugin: https://webpack.js.org/plugins/profiling-plugin/
JavaScript programmers, in my experience, don't really use profilers like "traditional" programmers do.
Maybe it's as much the tooling as it is the culture?
If said programmer doesn't use it, it's because they lack engineering maturity and competency.
There's no need to escalate into personal attacks.
Chrome's JS profiler is great, and is perfect for the kind of thing the OP is doing. But it's very rare that CPU cycles are a material problem in customer-facing JavaScript code, and it would be easy to get quite a few years into a career without ever getting exposure to it. I've had exactly one (very unusual) job where I used it frequently. The rest of the time, it pretty much collects dust.
https://github.com/alangpierce/sucrase
The real issue isn't JS, but is the lack of profiling (as shown here) combined with wanting to be everything to everyone leading to layers of bloated abstraction.
The dirty secret is, as Sucrase (https://github.com/alangpierce/sucrase) reveals, just that Babel is slow and the codebase really pays homage to the project name. Simply computing the config for transforms takes dozens of milliseconds on my machine as it does a bunch of filesystem reads.
So esbuild/swc etc. aren't gaining some magical compiled language speedup, they're just... not doing the dumb things that Babel is. Not ragging on Babel here, it's a 7 year old project originally written by a guy fresh out of high school. I bet a ground up rewrite of Babel could accomplish the same.
Yet it should be acknowledged that JS encourages various inefficient patterns.
Comparing with Rust, with which I am very familiar, I think that you’d be less likely to have most of the problems (some a little less, some a lot less):
• isBlockIgnored: it might still be tempting to do it the /…/.test(rule.toString()) way, but you’d be less likely to do it that way for two reasons: working with the actual AST is a good deal more pleasant than it is in JavaScript (due to a better type system, pattern matching and iteration tools), and you have to go a little further out of your way to use regular expressions since they’re not just built into the language.
• strongRound: somewhat less likely, because its inefficiency is more obvious, and because the developer is less likely to even find format!("{:.1$}", data[i], precision).parse().unwrap() than +data[i].toFixed(precision).
• stringifyNumber: similar remarks on regular expressions, you’re more likely to manipulate the strings rather than bothering with regular expressions (because they are a bother, even if minor, unlike in JavaScript).
• monkeys: well, in this case the issue is JS; the whole thing would be a non-issue in Rust.
• _loop: again JS problems and a misapplication of old-JS/new-JS–mixing techniques.
• semver: in good design this would be somewhat less likely in Rust because it’s likely to shift the parsing invocations to the caller in a way that makes the inefficiency a little more likely to be noticed, but in practice this would probably be about as likely to happen in Rust as in JavaScript.
And these are fairly tame cases, all things considered. Simplifying a bit, JavaScript makes it easy to do very inefficient things by accident, but Rust helps in many (though certainly far from all) cases, making it so that some of those can be optimised so that they aren’t inefficient after all, some simply don’t compile or can’t be expressed in the first place, and some must be expressed in slightly different ways that make the inefficiency more likely to be noticed and avoided.
—⁂—
You also should really specify that Sucrase achieves its speed by doing something completely different. SWC and esbuild are explicitly doing basically what Babel does, and so comparisons between them and Babel are meaningful, but comparisons with Sucrase cannot be used to vindicate JavaScript performance. Ports of what the likes of Sucrase or Bublé do to Rust or even Go would blow the corresponding JavaScript library out of the water.
https://github.com/alangpierce/sucrase/issues/730
JS JIT creators don't get enough credit for their string implementations. Not much comes close when you consider both performance and robustness they packed into the C++ implementations that JS is actually using.
I think the real point here is that more profiling could give some great results without tons of work.
The fact that half the comments here are dismissive or condescending is such a sad indictment of HN culture :(
Thanks for the kind words!
I'm also not keen on javascript minimization. Most of the delay on the client in not in the transport, but in the parsing. For this reason, I do think tree-shaking has good value.
Here's a basic How-to:
* Run node with `node --inspect <file>`
* Open Chrome and go to `chrome://inspect`
* After it finds your target, click the inspect button to launch a debugger.
To use with Node.js profiling, do the `node --inspect` and `chrome://inspect` steps, then save the profile as a .cpuprofile file and drag that file into speedscope.
Another thing I've found useful is programmatically starting/stopping the profiler using `console.profile()` and `console.profileEnd()`.
Answered this elsewhere here: It's the `--cpu-prof` argument with node and the resulting profile is loaded into speedscope.
for (const i = data.length; i-- > 0; ) {Whoops, good catch! That's definitely an error on my part. The original code uses `var` there. Thanks for pointing it out.
Javascript isn't going away tomorrow, even if a replacement was released tomorrow it would take years for all the web to move.
I'not arguing to remove javascript altogether, just to stop this bloat
I stopped reading there. This performance overhead is insignificant. The way to speed up libraries is to keep time complexity low; e.g. don't search through every item O(n) when you could just have done a constant time lookup O(1)... Or don't have nested for loops with O(n^2) complexity when the problem could have been solved with two non-nested loops in O(n) time (e.g. using a Set or Object for lookup).
> Config parsing as a whole takes 4.3 seconds
WTF! If parsing a config file takes more than 20 milliseconds, you've got some serious issues with your project... There is no excuse. Even if your project is highly complex and feature-rich, you can just break it up into smaller sub-projects.
This article doesn't give any useful info because the project it's analyzing is just so bad.
It's like watching a turtle complete a 100-meter race and then taking away the lesson that crawling on one's stomach isn't a great strategy for a human to win the 100-meter race at the Olympics. Duh!
The whole project is a giant flaming pile of garbage. There is no interesting lesson to learn from it. Functions named 'monkeys' or 'perItem' or 'strongRound'?... Class named 'ConditionalRuleset' (WTF is a conditional ruleset, why would any project need it??? This abstraction makes no sense). What about 'isBlockIgnored(ruleOrDeclaration)'? Sounds like unnecessary complexity bloat when devs keep inventing new abstractions to give themselves more billable hours of work.
I would jump dump all these bloated libraries and frameworks and start the project from scratch.
But maybe all of this is besides the point. It's unrealistic to do heavy duty processing in a dynamic language and expect that the JIT always saves us. In comparison, Python programmers suffer no illusions that their code is usually just "fast enough", and call out to external libraries when heavy duty processing is required. Modern browsers provide some of these optimized capabilities for JavaScript, and they should be used whenever possible.