Micro-optimizations #1

Micro-optimizations #1

Spread and Numbers

ยท

3 min read

Spread

The love, and arguebly one of my favourites, things of ES6 is the Spread-operator. This has made my work so much easier. Also, makes everything look so lovely!

Here comes the question:

Is the Spread-operator faster or slower than using the complete object?

As you can see, using the complete object everytime seems like a better choice. Except for readability, which I do prefer over a such small optimization.

Numbers

How about numbers? Imagine you're in an interview. The interviewer asks you how to parse an integer. You think to yourself:

Huh? That's a silly question.

Though, is it? Is it really a silly question? Well, I don't think it is, there are a magnitude of ways to parse an integer in JavaScript.

Imagine we have this variable

const n = "1";

How would you parse n into an integer d? You could for example do:

const d = parseInt(n);

Easy peasy! Well, if I were to be your interviewer, I'd say:

Sure, but are there any other ways?

To this, you should not hesitate, but prompt answer:

Yes! There are many ways. Do you want to see another?

Then you quickly write another way below like so:

const d = Number(n);

This would show that you do know some options, but what if you swiftly wrote below the like again, whilst talking

const d = +n;

I ofr one, would be super happy and kind of proud, that you'd know at least three options. I wouldn't have to more questions about numbers.

How about 10 options in total? Well, these might still just be some of the options, but heck. It's enough for a proper micro-benchmark.

In your journey of bettering yourself in the world of JS, you'd try such a benchmark, just to check which of those ten options is the best. Of course, this small website can't give you advice when to use which options in which situation, but it can help you along some of the way, but lowering the guess work.

I found the best options, both for readability and speed, is the parseInt(n, 10), as this actually tells the reader that it'll parse an integer n in the base 10 format.


{ Best, Mads Bram Cordes }

Did you find this article valuable?

Support Mads B. Cordes by becoming a sponsor. Any amount is appreciated!

ย