r/javascript • • Oct 09 '18

Writing Lighter, Faster JavaScript Functions

https://medium.com/p/c631739af349
40 Upvotes

23 comments sorted by

View all comments

119

u/PickledPokute Oct 09 '18 edited Oct 09 '18
function isStooge(name) {
  const STOOGES = ['Larry', 'Curly', 'Moe'];
  return STOOGES.includes(name);
};

While it is a small object, it is created every time the function runs.

This seems like one relatively simple and obvious optimisation for any javascript engine developer. It would be foolish that with all the work and money spent on chrome, firefox or any other browser, this one case was left unoptimised. Does the author think that javascript engines are written by neophytes? I did go and wrote a small test case for this and found no real performance difference between declaring the array outside the function or inside it (node).

This article smells terribly of premature optimisation, and worse yet, doesn't measure whether it's faster or not. It succumbs to one of the worst sins in optimisation - doing it prematurely and on a whim. Please don't be like the author and write optimisations only based on preconceptions and gut feelings.

40

u/MUDrummer Oct 09 '18

I was writing almost this exact same reply.

The only real way to optimize your code is to produce it and then profile it in as close to a production situation as you can get.

CPU flame graphs are a hugely underutilized tool that most developers either know nothing about, or don’t know how to generate and read.

25

u/MoTTs_ Oct 09 '18

I benched it.
http://jsbench.github.io/#ad5a3588a6fd15b5e6030310bc899e95

Results on Chrome especially were surprising. The class static method was the fastest. By far. By more than an order of magnitude. Of the others, the original "unoptimized" version was fastest.

FF and Edge behaved more like how we would naively expect. The original "unoptimized" version was slightly slowest, the others roughly on par with each other.

The lesson here: Don't assume. Measure.

2

u/TheGreatBugFucker Oct 10 '18

I was surprised to see FF about twice as fast as Chrome, excluding that one outlier in Chrome.