r/programming • • May 25 '19

Making the obvious code fast

https://jackmott.github.io/programming/2016/07/22/making-obvious-fast.html
1.3k Upvotes

263 comments sorted by

View all comments

282

u/Vega62a May 25 '19 edited May 25 '19

Great post. In particular the Javascript benchmarks were enlightening to me - syntactic sugar can be nice but not at the expense of orders of magnitude of performance. I'm definitely guilty of this myself.

103

u/threeys May 25 '19

I agree. Why is javascript’s map/reduce/filter so slow? I would have thought node’s engine would optimize away the complexity of the functions to at least some degree but it seems like it does not at all.

It makes me feel like putting some preprocessing optimizing layer to on top of node wouldn’t be such a bad idea.

66

u/Kapps May 25 '19

For one, they’re not lazy. When you combine multiple functions like that in languages like C# with Linq or D with ranges, they’re calling 3 functions on one input.

In Javascript you’re taking an array, calling map which generates a new 32 million entry array, then filter which introduces a new one, etc.

→ More replies (9)

42

u/Vega62a May 25 '19

Yeah, I'm not really sure. I know there is essentially added overhead with each iteration in map/reduce/all of those other non-imperative methods, but it seems like Javascript got it really wrong.

Now, that said, in many cases it can still be six of one, half-dozen of the other, and readability / syntatic sugar is valuable. But I think this article illustrates that it's important to at least be thoughtful employing such tools.

64

u/threeys May 25 '19

IMO we shouldn’t have to sacrifice readability at all to achieve optimal performance. The ideal situation would be that any higher-level function would be optimized by the compiler to be just as performant as a lower-level one.

But maybe that is a much more difficult task than I realize.

36

u/Vega62a May 25 '19 edited May 25 '19

That would definitely be nice - but I think, as you said, it's definitely a nontrivial task. A lot of javascript's non-imperative methods play a lot of games with scope and context (what's returned when you invoke "this") and translating that feels like it would be very tricky. A comment chain elsewhere on this thread highlights a bit of it - consider the different ways Javascript hoists and scopes variables. If, for example your compiler "optimized" an anoymous inner function within a map call into an imperative loop under the sheets, that would screw up all of your variable scoping with let and var and there may not be a way to recover.

→ More replies (7)

21

u/carnivorixus May 25 '19

Lookup lamba lifting and defunctionalization, this is only the tip of the iceberg but it gives a nice perspective on why things are difficult. It mostly has to do with that a function in JavaScript is not just a function it has a lexical scope which is captured, i.e. closures. When you compile this down to a low level language without closures you need to represent the variables in scope, this is usually called the environment of the closure. Now depending on the use of the function this might not be needed. But to be sure that this is not needed you need to first perform static analysis which consists of computing fixpoints which might or might not terminate. Because you need it to terminate you have to start making over approximations. JIT compilers are so good at what they do because the amount of information you have at runtime is bigger than statically... you see how this is fast becoming complex :)

17

u/hegbork May 25 '19 edited May 25 '19

To optimize everything that people think a compiler "should" optimize quickly leads to needing the compiler to solve the halting problem.

The (future) compiler will solve it has been a constant mantra of higher level languages since I started writing code and for those 30 years I still haven't met a problem where I can't manually outoptimize compiler generated code. In most cases it's not worth the effort, but sometimes it saves the client buying 60 machines in the next upgrade cycle.

5

u/DidiBear May 25 '19

Java (1.8) and Python (3) solve this problem by making map/filter/reduce lazy by default. That's a non sense Js doesn't permit it in some way

5

u/Smallpaul May 26 '19

Laziness is not always faster. Can be slower in many cases.

→ More replies (15)

36

u/Retsam19 May 25 '19

I would have thought node’s engine would optimize away the complexity of the functions to at least some degree but it seems like it does not at all.

It might, nowadays. They ran these benchmarks on an older version of node (v6), while newer versions of node ship with a new V8 engine which is much more performant.

12

u/NoInkling May 26 '19 edited May 26 '19

Yeah I'd like to see this benchmark redone on Node 12 to see what difference there is.

7

u/dksiyc May 26 '19
nodejs
v10.15.3
map reduce x 0.22 ops/sec ±1.71% (5 runs sampled)
reduce x 2.45 ops/sec ±2.02% (11 runs sampled)
foreach x 0.54 ops/sec ±4.73% (6 runs sampled)
imperative x 36.62 ops/sec ±1.22% (64 runs sampled)

nodejs
v11.15.0
map reduce x 0.20 ops/sec ±2.04% (5 runs sampled)
reduce x 2.28 ops/sec ±2.86% (10 runs sampled)
foreach x 0.72 ops/sec ±6.40% (6 runs sampled)
imperative x 37.65 ops/sec ±0.83% (65 runs sampled)

nodejs
v12.3.1
imperative x 39.18 ops/sec ±0.46% (51 runs sampled)
foreach x 1.30 ops/sec ±2.75% (8 runs sampled)
reduce x 2.12 ops/sec ±3.91% (10 runs sampled)
# map reduce either hangs or takes forever

13

u/Smallpaul May 25 '19 edited May 25 '19

It is extremely difficult for the compiler to be sure that the map and filter functions that the programmer expects to execute have the same semantics as the map and filter in the language standard. It doesn’t generally know the types of the variables nor whether the methods have been overridden at runtime.

→ More replies (3)

6

u/binkarus May 25 '19

The stack frames required for each function call can't be easily optimized away from the JIT. In AOT compiled languages, these can usually be nicely inlined, but the same is not true of Javascript unless you use a restricted subset of Javascript. If you are trying to solve the general case, then you have to allow for this. which causes problems.

→ More replies (4)

84

u/SocialAnxietyFighter May 25 '19

Depends on what you are doing inside the loop. If every loop takes 10ms to run your times will be very comparable for a large number of loops

45

u/Vega62a May 25 '19

That's fair - but, what I was getting at is that I feel often that writing the same thing several ways (especially for very simple tasks like summing) is viewed as a "6 of one, half-dozen of the other" choice, and this post highlights that this is not always the case.

80

u/Retsam19 May 25 '19 edited May 25 '19

IMO, writing JS code in for-loops because "they're faster than the .map/.reduce/.forEach" is almost always going to be a non-optimization: websites have performance issues, but it's almost never because JS is inefficiently looping over millions of items in an array.

The real performance killers in websites are generally things like network requests, DOM operations, expensive styles, or some framework-specific operations. It's very rare that array operations are the performance bottleneck, so "optimizing" them won't give meaningful gains. The first rule of optimizing is picking the right thing to optimize.

For the vast majority of JS use cases, I'd recommend writing array loops in whatever way is most readable, not what's hypothetically fastest. If you think that's the for-loop, great. But, personally, I'd much rather read this code, though:

values.map(x => x * x)
    .reduce((a, b) => a + b)

And of course, with this trivial operation the code style doesn't matter much - either way is pretty readable - but the more complex the logic, the more the code benefits from the FP style.

38

u/binkarus May 25 '19

What you're saying is "profile your code and don't do meaningless optimizations." I especially agree in the case of Javascript because the semantics of the built in constructs for for loops can be error prone. In a not-insignificant way, base Javascript is very error prone, which is why many libraries exist. Therefore, using lodash is a good idea for monomorphizing your iterator interfaces.

Additionally, Chrome's profiler is extremely good for being able to identify hot loops, so there really is no excuse for not profiling to find out the problem.

5

u/Vega62a May 25 '19

I'd say broadly you're correct, but again, I'm definitely not advocating for kicking map/forEach loops back in code reviews. More that it's important to be thoughtful because there are going to be some cases where it does make a difference, and most of those cases are iterating over large amounts of data, which is a point at which it's important to be thoughtful anyway.

→ More replies (1)

5

u/aquapendulum2 May 26 '19

Note: This becomes a different story in Electron applications. Electron apps don't incur network latency just to serve an interface, which means JS can be next in line to cause bottlenecks.

→ More replies (5)

7

u/[deleted] May 25 '19

His JS code is suboptimal, isn't it? He's redeclaring x inside the loop every time with var x = values[i]. I'd expect it to be faster if he declares var x; outside the loop once and then only reassigns it inside the loop.

38

u/stratoscope May 25 '19

No, var is scoped to the function, not to the inner loop, so moving it outside the loop would not change anything.

It might be different if the code used let which is scoped to the inner block.

8

u/Vega62a May 25 '19

Good catch. JS Hoisting is weird.

8

u/Vega62a May 25 '19 edited May 25 '19

Edit: /u/stratoscope is correct, because the author used var the redeclaration winds up not having any impact at all. JS hoisting is weird.

My original comment below: (which is still relevant, but incorrectly assumes a conflation of let and var scoping).

Sure, but the imperative code, even suboptimal as it is, is *still* the fastest and it's not close.

With that said, given that Javascript is weakly typed, my suspicion is that a reassignment of a variable still often results in new heap space allocation (since there's no guarantee at all that the new variable occupies the same amount of space as the old one) so I don't know how much of a performance impact your comment would make in isolation. (Certainly in the context of wider execution, he's hammering on the gc way more than he needs to and that can have wider ramifications).

→ More replies (2)
→ More replies (2)
→ More replies (9)