DEV Community

Stop Writing JavaScript Like This

Ruben Gabrielyan on October 14, 2021

Most of us are used to writing JavaScript code for a long time. But we might not have updated ourselves with new features which can solve your issu...
Collapse
 
akashkava profile image
Akash Kava • Edited

Do some performance testing of both codes in first example and see the difference

On both iOS Safari/Chrome/Firefox it is 90% slower, on Desktop except chrome, Safari and Firefox are 90% slower.

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
peerreynders profile image
peerreynders • Edited

This is a classic case of tunnel-visioning into premature optimization.

It's also exhausting how often claiming "premature optimization" is used to justify sloppy thinking.

Don’t pessimize prematurely:

Easy on yourself, easy on the code: All other things being equal, notably code complexity and readability, certain efficient design patterns and coding idioms should just flow naturally from your fingertips and are no harder to write than the pessimized alternatives. This is not premature optimization; it is avoiding gratuitous pessimization.

Early optimization is the root of all evils," Knuth said, but on the other hand, "belated pessimization is the leaf of no good," according to Len Lattanzi.

Alexandrescu, Andrei. "Modern C++ Design: Generic Programming and Design Patterns Applied", Small Object Allocation, p.77, 2001.

Stated differently:

Don't fetishise the quick-and-dirty. Sometimes you'll save yourself a world of hurt by doing The Right Thing in the first place.

Rich Hickey:

Programmers know the benefit of everything and the tradeoffs of nothing.

V8 is an amazing piece of technology but its heuristics are so complex that the smallest thing can derail JavaScript performance, so it's very inconsistent — at least when compared to languages that are compiled prior to deployment. From that perspective it makes sense to feed it code where is doesn't have to "guess" too much.

WebAssembly for Web Developers (Google I/O ’19):

Both JavaScript and WebAssembly have the same peak performance. They are equally fast. But it is much easier to stay on the fast path with WebAssembly than it is with JavaScript. Or the other way around. It is way too easy sometimes to unknowingly and unintentionally end up in a slow path in your JavaScript engine than it is in the WebAssembly engine.

And finally in the face of the continued proliferation of low-power / low-end / low-spec / small-core devices it seems foolish to rely on the JIT having access to the necessary CPU cycles to reliably optimize the code in a reasonable amount of time at runtime (perhaps we need profiling transpilers - but establishing representative "real-world" operational profile(s) can be a challenge in itself).

Meanwhile the self-improvement industry is pushing for aggregation of marginal gains - which is all about eliminating pessimization.

Thread Thread
 
Sloan, the sloth mascot
Comment deleted
 
peerreynders profile image
peerreynders

In the meantime real-life users have to deal with this.

Thread Thread
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
kettanaito profile image
Artem Zakharchenko

Instead of writing that outdated ||, use the new ?? operator:

|| is as outdated as function. These two operator have two drastically different semantics:

  • || in case left-hand value is falsy.
  • ?? in case left-hand value is not defined (undefined or null).

Both have their usage and are not interchangeable. ?? is great when false is an intentional value.

Parenthesis in functions is not something you should spend your time on, use Prettier.

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

On Firefox, the || method was almost twice as fast as includes. So, if there's almost no difference on Chrome, and a big difference in favour of || on Firefox, || would seem the better choice overall for performance? jsbench.me/njkuruuurr/1

Collapse
 
akashkava profile image
Akash Kava • Edited

On mobile, difference is 90%, try it and then see. You are creating an array, unnecessary memory allocation and calling a method, which are multiple cpu cycles. Compound it multiple time used in single script it is by far the worst practice. Test on iPhone

Thread Thread
 
echofly profile image
echofly

90% ? are you kidding me ? talk is cheap, show me your testing.

 
peerreynders profile image
peerreynders • Edited

Globally Apple has a 15% Marketshare, 53% in North America, 32% in Europe — those users are locked into a "shitty browser" and not willing to forego their other creature comforts they are not going to switch brands on your account.

Meanwhile Chrome even on desktop has a reputation for being CPU and memory hungry. Apparently some people want lighter-weight alternatives. One has to wonder how pessimized JavaScript performs on Google GO on a "shitty phone".

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli

Strong disagree on using => over function. You'll have a confusing time with this.

Collapse
 
antonmelnyk profile image
Anton Melnyk

You should not use "this" in modern JavaScript in the first place.

Collapse
 
mellen profile image
Matt Ellen-Tsivintzeli

Because?

Thread Thread
 
ifarmgolems profile image
Patrik Jajcay

Because it doesn't promote arguably better immutable state.

But hey, it's a bold statement and I wouldn't say it always applies.

Collapse
 
jamesthomson profile image
James Thomson

For #1, another option is to use find instead. That way it stops execution on the first found match.

 
peerreynders profile image
peerreynders • Edited

iPhone 6s Plus iOS 14.7.1
jsbench results
perflink results

While Safari is primarily to blame here, this phone's CPU is still better than what's on a lot of contemporary run-of-mill android phones.

2019 Geekbench scores

Collapse
 
pavelloz profile image
Paweł Kowalski

Its impossible to respond in a thread after some levels of nesting so I will just go and post in top level adding to one part of it:

So many JS articles have people in the comments section bickering about performance and citing arbitrary benchmark metrics as proof.

I also think people think about "performance" too narrowly. Developers performance matters. Especially since JIT compilers progress every year and find new ways of applying those microoptimizations. In the IE days it was very often the case that one microoptimization would be an antipattern next version, because engine strategy was so much better.

Collapse
 
ravavyr profile image
Ravavyr

These are good tips:

  1. The performance difference is irrelevant, the array includes way feels cleaner but is actually harder to read because you don't immediately see what you're comparing the value to, and the more items in the list, the farther away the variable is visually so it actually makes the code harder to understand for even slightly more complex lists.

  2. Optional chaining is terrible terrible and let me say it again, terrible.
    See. If obj?.address?.postalCode fails, you don't know if obj doesn't exist, or obj.address doesn't exist or if it's just the obj.address.postalCode that's missing.
    This WILL [not can] lead to problems where no error happens even though an important piece of information is missing and debugging it is a mess where you end up splitting it up anyway so it's better to validate each part of the object exists before using it.

  3. You'll never do second=first....if so you would just use "first" in the first place.
    That scenario literally never happens unless you're writing extra code and creating extra variables you don't need.

  4. I like this one, i usually use arrays for it, but objects work too.

  5. If a function has one line in it...it shouldn't be a damn function. That level of abstraction makes systems a bloody nightmare to debug because you're jumping 20 functions deep to find the culprit and often in 20 different files. Just KISS dammit.

Collapse
 
jonrandy profile image
Jon Randy 🎖️

Would be interesting to also see performance benchmarks on each pair

Collapse
 
macsikora profile image
Pragmatic Maciej

Such posts always inspire me to write another article why radical opinions are always wrong.

Collapse
 
alexhutchisondev profile image
AlexHutchison-Dev

Owning an iPhone doesn’t mean you have to use safari, it is the default sure but you can install Firefox, brave, or if spyware is your jam Chrome.

Collapse
 
miketalbot profile image
Mike Talbot ⭐

But those browsers all use the Safari engine under the hood, Apple won't allow anything else

 
kettanaito profile image
Artem Zakharchenko

Yeah, that's why I mentioned "falsy" values, not false explicitly.

Collapse
 
mastodonnine profile image
Mastodon9

Where can you learn more tricks like this?

 
akashkava profile image
Akash Kava

Android has V8 engine so it performs same as desktop, Safari and Firefox has different results.

 
akashkava profile image
Akash Kava

Is it Android or iPhone?

Collapse
 
mynameisxue profile image
XueZC

let first = 0
const second = first || ''
second // ''