Here are some Tips & Tricks that have been shared by our regular participants which should help you attain a better score in the challenges.
Disclaimer: since the principles in real life differ greatly from coding challenges, don't treat these as suggestions for good code. In real life maintainability, readability and simplicity plays a far more important role. Performance comes into play only when you are dealing with particular bottlenecks. For example, you might want to optimize aggressively if you are dealing with sophisticated computation in an event listener for a scroll event. And currently I can't think of a plausible real life scenario where codegolf principles would be useful :)
We can split the tips & tricks into sections for Macro, Micro and Codegolf.
Macro-optimizations are what you apply in the real world if there's a (potential) performance bottleneck. Micro-optimizations are what you apply in the real world if you hate your colleagues. - Peter-Paul
- Google is your friend :) a lot of problems have been solved already and/or have optimal solutions for them. Try to find and understand them, and modify if needed (Irene)
- When doing optimizations run multiple, slightly modified solutions against each other to see which one consistently comes out top (Irene)
- avoid unnecessary loops (and other things that affect time complexity order), how trubofan and other optimizing compilers work, etc. (Peter-Paul)
- assigning new memory and/or making garbage collection kick in costs time, so avoid creating a new array with
[...oldItems, newItem]
unnecessarily, but push to an existing array, if possible (Harijs) - can use a Map or object to store intermediary results so you can reuse those (Jan Bart)
- use for loops where possible (instead .forEach) (Jan Bart)
- consider if there is stuff you can pre-generate (the prime number, for instance)(Jan Bart)
- creating objects is expensive, so make them first and then fill them (Dexter)
- function calls are expensive (Dexter)
- lookups from nested closures take longer than local variables (Dexter)
- be aware that a lot of functions in Javascript are just syntactic sugar (think of
.map
,.reduce
,.filter
, etc.) that do loops under the hood. Depending on your use case, a plain ol'for
orwhile
loop can be faster (Irene) - go for mathematical solutions if possible (see W12 for example) (Irene)
~~n
is faster thann|0
(Peter-Paul)- for string manipulation, it seems best to use the ‘+’ sign rather than templates (Jan Bart)
- as a general tip - knowing JS API surface helps a lot, so reading through documentation (1 2) regularly will not only let you find short solutions, but be a really knowledgeable developer (Harijs)
- study older code golf submissions for ideas (Irene)
- read tips-for-golfing-in-javascript and tips-for-golfing-in-ecmascript-6-and-above because they cover a lot of cases (Irene)
- declaring objects in arguments saves declarations (Dexter)