237 points · by davidbarker · 6y ago · 179 comments
As an aside, I’ve been seeing a number of articles show up that basically go like “Chrome implements x efficiently but semantically equivalent y poorly, you should use always use x”. I really hope we don’t end up with JavaScript code being written to be optimized well on one particular implementation of a JavaScript engine…it’s interesting to see this in this area specifically because other VMs (e.g. Java) have knobs you can turn yourself but with JavaScript your code runs without much input on your side, so methods to influence the VM are much more specific…
for (var i = 0, len = arr.length; i < len; ++i) { ... }
Hell, the whole premise for React (the virtual DOM) is based on outdated performance advice. Chrome has used a dirty-bit for DOM manipulations since a year or two after React came out; manipulating the DOM is within a factor of ~2-4 of setting a property on a JS object (and much faster than constructing & copying whole new JS objects, which incurs a GC cost), it's just that you really want to avoid interspersed manipulations & queries, which force a page reflow: parent.appendChild(document.createElement('div')); // Fast; ~50 us
let w = parent.innerWidth; // Slow, forces reflow; ~20 ms
let h = parent.innerHeight; // Fast again; no page modifications
parent.appendChild(document.createElement('div')); // Fast; just sets dirty bit
parent.appendChild(document.createElement('div')); // Still fast; dirty bit already set
But that's the nature of a lot of technical rules of thumb. They get stale as the underlying stack beneath them changes.This mentality sorta falls into the exact pitfall GP mentioned (i.e. what you really want is for IE/Edge to be significantly faster bringing speed gains for everyone else along the way, not for Chrome to be microscopically faster at the expense of every other browser)
There are real and significant costs in things like random access of .childNodes or bottom-up DOM construction in some browsers. At the height of the whole virtual dom thing, there was a lot of super browser-specific micro-optimizations going on, a lot of it w/ a heavy focus on Chrome, with IRHydra and stuff.
It got a bit ridiculous when I figured out that you could make a significant dent in one of the popular benchmarks at the time not by tweaking JS anymore, but by removing unused CSS rules from bootstrap.css...
But as you said, engines change quickly and I'm not sure it's really worth to be chasing micro-optimizations anymore. We're getting to a stage where the only way to get faster is to simply run less code. Some frameworks are getting the idea (svelte, marko).
I was a big fan of Polymer/WebComponents in 2014, but they kinda dropped the ball. In hindsight I wish they'd just implemented the React API directly in the browser. (Though depending on how Google vs. Oracle goes in the Supreme Court, maybe that'll become illegal, sigh.)
The benefit of React (if any; it has a lot more overhead than vanilla JS+DOM) is that you can't hit that specific pitfall of forcing layout interspersed with DOM or style manipulation.
Could you explain why?
Is the following true even when the parent is already in the DOM?
parent.appendChild(document.createElement('div')); // Fast; ~50 us
let w = parent.innerWidth; // Slow, forces reflow; ~20 msThis isn't true though, useLayoutEffects that perform a read/write littered through your code is going to quite easily induce layout thrashing and there's no way of splitting this throughout a tree
It doesn't really matter nowadays anyway, because now I write my for-each loops like:
for (let elem : arr) { ... }
or arr.foreach(elem => { ... });
(Well, technically now I write Android & C++ code and do leadership/communication stuff, but I brushed up on my ES6 before getting the most recent job.) let index = arr.length;
do {
index -= 1;
console.log(arr[index]);
} while (index > 0);
As a side note whether it takes longer to access a variable or object property is largely superficial depending upon the size of object because it implies creating a new variable on which to store that object property. There is time involved to invoke a new variable just as there is time involved to access an object's property.As an added bit of trivia in the 1970s a software developer named Paul Heckel, known for Heckel Diff algorithm, discovered that access to object properties is faster than accessing array indexes half the time. That was in C language, but it holds true in JavaScript.
A good compiler will make it so that they are largely equivalent. In C-based languages this is one of the first things a compiler will do, and I am sure that every JavaScript engine does this kind of thing too when possible (actually, it may even have an easier time doing it because it may be able to skip pointer analysis).
Previously we had been doing retained-mode rendering. We would modify & shuffle around the pieces of the page.
React's components were there to let you re-render the app quickly. When state changed, a new render happened, with new elements emitted. You didn't think of what elements used to be there.
React was about the virtual dom. It was about creating an abstraction to let us not have to regard what was on the page, when we were deciding what is on the page. Incidentally, imo, that involved components, but components, while comprising numerous html elements, serve a very similar function to html elements (especially to web components), and were not, imo, a particularly novel part of React. Yes, there was a lot to their creation & implementation, there was a lot of tech work that went into making Components a thing. But components, to me, are far outshadowed by the vdom, by the performance & speed of a data-system designed to go diff & en-act desired state into the live DOM tree.
In kubernetes world, we'd call the vdom a controller. It reads the canonical state, the component tree, and insures the target DOM machinery is kept up to date & reflects this desired state.
I do not, mostly because I came online at a time that Internet Explorer was already uncool and Mozilla was clearly better, and also I had no idea what JavaScript was ;) But I can only imagine what the browser monoculture of the time was like, viewing the echo of it many years later with Blink.
> I think I can reproduce this behavior on Figma's code base too. I've never noticed because we use Chrome pretty much exclusively for development.
We're already there. Chrome dominates so much of the dev market, so naturally v8 is what people are optimising towards.
Because of a perf bug in WebKit they added a flag to generate less correct code that is fast in WebKit.
If anything, it's a case of optimizing towards WebKit.
But really, it's a case of performance bug in WebKit and them adding a work-around.
Hopefully they're always treated like bugs and not something we need to work around.
The problem is that when implementing improvements it's easy to forget every mostly-equivalent thing and so miss obvious things (often the entire fix in the end is "if (canDoItFast) doTheExistingFastThing()"
I mean I'm sure they have a solution, since this seems like a rare occurrence.
I will note though that const/let are not mostly equivalent to var. They're often used interchangeably, but they work pretty differently as far as a JS engine is concerned.
Hopefully this changes, even slowly, but it'll probably take a while since Chrome's got so much share.
Well we know pizlonator hangs around on HN from time to time :) Especially on topic of JS and Webkit.
You're late by many years, most frontend developers have been explicitly optimizing for Chrome for a long time now.
But, I think a more relevant example might be people who write code prefixed with comments like "Destructure this manually. At -O2 on GCC this allows the first field to be placed in a register" which is putting waaay too much dependence on the internals of a specific implementation, beyond even whatever extensions a particular compiler claims to support.
Because I have seen those kind of discussions too many often, even back on Usenet days, like the example you point out.
I'm afraid that ship has already sailed.
This seems bad.
We tend to think that newer is better and faster, but it's also wise to think that old apis had to be fast on old hardware. Hardware that is not the target of new APIs.
Also, block-scoping is a language feature that's fundamental to virtually every other modern language out there. This isn't some high-falutin' new API. This is basic.
IE 8 got querySelector before IE 9 got getElementsByClassName, so it’s not really an old vs. new thing, and I don’t think anyone expects querySelector to be faster than getElementById.
> I think I can reproduce this behavior on Figma's code base too. I've never noticed because we use Chrome pretty much exclusively for development.
I'm more and more concerned that the monoculture of chrome for developer tooling is making the web a worse place...
while true {
let hello = "world";
}
The scope would keep getting freed then re-allocated, which will be slower than simply continuously setting an existing variable's memory location over and over again.`let` can be changed so cannot be optimized out this way (at least not without doing more complex analysis and proving that the variable is not being changed).
node let.js 7.00s user 1.35s system 51% cpu 16.272 total
node var.js 7.21s user 1.22s system 55% cpu 15.183 total
go run main.go 0.80s user 0.94s system 17% cpu 10.064 total
I feel like that is about the best we can do without harming backwards compatibility. They are there when needed, but we are stuck with the ambiguous "number" type in general.
It's kind of pointless to even try and optimize for things like this because there's a very good chance that it can change in the news few weeks/months/years.
It also allows me to build sites which work in Netscape 3.0 and up without any special compatibility modes. :)
For instance, "var" may seem easier, but "const" is definitely less complicated. "var" has unintuitive edge cases with closures that "const" does not. `var` is also scoped to the nearest function rather than the nearest block, a "feature" that has tripped up many a new JS developer. `const` has none of these surprises.
Would love to see what semantics are making let/const abysmal.
(I don't care if I get a million down votes, I really don't. You're all misusing const and you know it. It's a shitty hack turned into a fad by someone who didn't understand the language.)
Also, in general, using the most limited constructs that fit your use case makes a tonne of sense for code cleanliness, in any language. For example, in a language supporting private/protected/public properties and methods, you should always default to private, as that’s most limited and easiest to reason about. Then make it more public as necessary. Same goes for const vs. let - const is more limited, it’s a better default choice, only use let if you actually need to re-assign it. Using const means there’s one less thing for readers of the code to worry about, it’s a variable that CAN’T be reassigned, the same way you don’t have to worry about a private method being called externally.
This is, essentially, the “principle of least power.”
Also, if you’re talking about leaving mutability like this in the code long term, this really only applies to GLOBAL mutable state, and global mutable state is a terrible thing for code maintainability in any language. If it’s not global, you can’t fiddle with it later in the console anyways. Littering your program with global mutable state just because “someday, someone may want to fiddle with this in the console, and this makes that slightly easier”, that’s just not a reasonable argument.
You're welcome to go use another language that doesn't have a formal spec, if you're so inclined to disagree with what the spec for this one says.
const improves readability, and the ability to reason about code. It lessens the need to exhaustively scan the code looking for other assignments to the variable.
const foo = {};
foo = 42; //not allowed
foo.bar = 'baz'; //this is fineIt’s the same behaviour in many other languages.
Why would rebinding variables ever be a good thing?
const fixed the pointer but don't prevent user change the value in the storage it point to.
const foo = #{};
foo = 42; //not allowed
foo.bar = 'baz'; //not allowed
https://2ality.com/2020/05/records-tuples-first-look.html