r/javascript • • Oct 09 '18

Writing Lighter, Faster JavaScript Functions

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

23 comments sorted by

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.

16

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

90% sure the engine will tag that array for re-use.

In fact, wasn't the cause of that recent iOS 12 array reversal issue that mutated array literals were being re-used inappropriately?

5

u/gsnedders Oct 09 '18

In fact, wasn't the cause of that recent iOS 12 array reversal issue that mutated array literals were being re-used inappropriately?

Ding-ding-ding! Yes. JSC does copy-on-write of arrays and objects consisting purely of literals.

9

u/sumdudeinhisundrware Oct 09 '18

Why can't we have nice things like peer review to prevent crap like this from being published?

12

u/rangeDSP Oct 09 '18

If you read the other comments, looks like the peer review is happening right here.

2

u/sumdudeinhisundrware Oct 09 '18

Yeah but this got out and impressionable engineers are putting it into practice and screwing up production code. I guarantee it.

2

u/rangeDSP Oct 09 '18

This is an inherit problem with open platforms, internet / web dev community / reddit gives people a way to share their opinion without gatekeeping and censorship. The obvious downside is quality control and potentially biased content.

The developer needs to learn to have diligence and do their own research, can't really stop them from doing bad things really. And the community needs to call out bad articles as they come along.

6

u/gigglefarting Oct 09 '18

Are those chives on a cupcake?

3

u/zephyrtr Oct 09 '18

Pistachio shavings

1

u/gigglefarting Oct 09 '18

I guess that's better, but not by much.

4

u/AceBacker Oct 09 '18

It is pretty rare that optimizations in code matters that much. Usually optimization matters when hitting a slower tech like a database query. Out in your middleware code just keep the loops to a minimum and you should be fine. usually anyway. I much prefer readable code even if it is not micro-optimized.

3

u/coverslide Oct 09 '18

Ok he touts this as faster or better optimized, but doesn't give any benchmarks or anything to back up those claims?

2

u/nullified- Oct 09 '18

Performance issues aside, when would one be inclined to write a function like this "unoptimized" one?

An array literal inside a function that checks if the array contains an item is beyond contrived. Hence, I'm having trouble generalizing this pattern to something not contrived.

1

u/hypernautical Oct 10 '18 edited Oct 10 '18

I tend to write lots of functions that reference a constant object in two situations currently. One is to check an argument against a list of types that have one response vs. a more common one. This avoids long IF clause with lots of ORs:

function getUserDisplayName (userObject) {
    const userTypesWithTitles = [1, 2, 3, 5]
    if (userTypesWithTitles.includes(userObject.type)) {
        return `${userObject.title} ${userObject.name}`
    } else {
        return `${userObject.name}`
    }
}

The second use is also avoiding lots if IF...ELSE IF.. clauses using a "map":

function getUserLongTitle (userObject) {
    const userLongTitleMap = {
        'ceo': 'Chief Executive Officer',
        'cfo': 'Chief Financial Officer',
        'coo': 'Chief Operations Officer
    }
    return userLongTitleMap[userObject.shortTitle]
}

I use these all the time, mostly the latter, when I know there are particular front-end display requirements beyond the virgin data sent to me by the server. The former could also be used for permission or different content display booleans, etc.

1

u/cLnYze19N Oct 09 '18

Regardless of whether the described methods have any merit, can anyone answer why it was written this way:

const isStooge = (function() {
  const STOOGES = ['Larry', 'Curly', 'Moe'];
  return (name) => STOOGES.includes(name);
})();
isStooge('Moe');
isStooge('Joe');

And not this way:

const isStooge = (() => {
  const STOOGES = ['Larry', 'Curly', 'Moe'];
  return (name) => STOOGES.includes(name);
})();
isStooge('Moe');
isStooge('Joe');

Why the mix in function syntax?

2

u/Dynamicic Oct 10 '18

I was thinking the exact same. The inconsistency was triggering my OCD.

1

u/nullified- Oct 10 '18

This makes sense. I do this myself a lot, I've just never been inclined to include the object or array in the function body.

-30

u/DAZNeng Oct 09 '18

Great read, shared within our teams - thanks!!

37

u/PointOneXDeveloper Oct 09 '18

Please don't, this is not actually a good idea.