DEV Community

Discussion on: 15 Killer 🗡 JS techniques you've probably never heard of 🔈🔥

Collapse
 
lionelrowe profile image
lionel-rowe

Avoiding Number is considerably better for performance

I'm extremely sceptical about this, as any JS engine worth its salt should be able to figure out that +x has identical semantics to Number(x).

JSBench confirms no noticeable difference (Chrome 110 on Windows 11) jsbench.me/c9le9hworr/1

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

I tried perf.link - was faster every time (Firefox and Chrome, Linux and Win11) - up to 30% faster in fact

Thread Thread
 
thethirdrace profile image
TheThirdRace

Even if it's 30% faster, it won't matter in the end.

Why? because you won't use +x or Number(x) with 1 million operations in a second. You'll use it 99% of the time less than 3 times in a row. 30% is worthless here.

But using Number(x) makes it very easy to understand the intention of the code.

Using +x will be missed by a lot of devs and will only cause trouble.

Readability over pretty much anything, except when you absolutely need the performance, which is very rare. And if you disagree with this, then let's just agree to disagree...

Thread Thread
 
lionelrowe profile image
lionel-rowe • Edited

Agree with this. Number is much more noticeable at-a-glance in the source code, whereas any minor improvement in perf doesn't make any practical difference and could easily be erased or reversed by future engine optimizations in any case.

Small correction to my original comment, though — it turns out that since the introduction of the bigint data type, +x and Number(x) are no longer semantically identical: Number(1n) gives 1, whereas +1n throws an error, because bigints can only be explicitly converted to numbers, not coerced. IMO, this is another argument in favor of Number(x), as it consistently works for all data types of x, without throwing (unless you do something crazy like x = { valueOf() { throw '' } }).