I agree that performance matters. But premature optimization is the root of all evil. In most cases code readability is more important than optimization tricks. Do optimizations when you really need them.
Speaking of your first example, I think the most performant and at the same time readable way to solve the problem would be old good for loop:
It is much faster to add an item to a Set than to an array using push() or unshift().
pushing an item to an array is fast, it's complexity is O(1). Appending an element with unshift is indeed slow (O(n)), because it requires reassigning all indexes in the array.
You cannot use indexOf() or includes() to find the value NaN, while a Set is able to store this value.
Thanks for taking the time and pointing these out.
100% agree with your point on readability. But your example is another indicator that there are many ways to solve a problem and we should choose one which helps performance.
You say that it's good for performance to reuse functions (react classes and nexted functions examples). But in the beginning of the article when optimising chain functions you keep to use arrow functions in forEach and reduce methods.
My example with for loop is faster than using forEach or reduce examples.
I just don't feel consistency between your examples. Also if the focus of your article is performance then please show the most performant way (without sacrificing readabilty) instead of half-performant.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I agree that performance matters. But premature optimization is the root of all evil. In most cases code readability is more important than optimization tricks. Do optimizations when you really need them.
Speaking of your first example, I think the most performant and at the same time readable way to solve the problem would be old good for loop:
Readable and performant.
push
ing an item to an array is fast, it's complexity is O(1). Appending an element withunshift
is indeed slow (O(n)), because it requires reassigning all indexes in the array.Thanks for taking the time and pointing these out.
100% agree with your point on readability. But your example is another indicator that there are many ways to solve a problem and we should choose one which helps performance.
Will update the includes part ๐
You say that it's good for performance to reuse functions (react classes and nexted functions examples). But in the beginning of the article when optimising chain functions you keep to use arrow functions in
forEach
andreduce
methods.My example with
for
loop is faster than usingforEach
orreduce
examples.I just don't feel consistency between your examples. Also if the focus of your article is performance then please show the most performant way (without sacrificing readabilty) instead of half-performant.