r/programming • • Apr 17 '19

Making the obvious code fast

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

76 comments sorted by

View all comments

42

u/gbalduzzi Apr 17 '19

Holy shit the difference in JS performance is incredible, mainly considering how the community and the frameworks documentation usually recommends the more fancy approaches instead of the good old for loop,.

28

u/wavefunctionp Apr 17 '19

It's unclear if the same optimizations would be available in real code. Microbenchmarks are notoriously unreliable with modern engines. For instance, if the compiler has access to the values in code, the compiler could just be unrolling the for loop or something.

22

u/bobappleyard Apr 17 '19

JavaScript interpreters have got pretty fast when you don't use the fancy features. Problem is everyone uses the fancy features all the time.

1

u/James20k Apr 18 '19

I wish this were true, but I've gotten massive speedups in JS code by manually folding constants, and reimplementing functions which have constant parameters which results in constant folding once inlined

3

u/curious_s Apr 18 '19

I have used a for loop in JavaScript for a slow search function and it sped the code up by a significant amount. I think the best idea is to try and measure, the array prototype functions create cleaner code than a for loop which is an important factor.

8

u/[deleted] Apr 17 '19

I believe most browsers have improved those cases a lot since I wrote that, someone should check and report back.

3

u/Aetheus Apr 18 '19

Yeah. ~10000ms down to ~30ms is just insane. Granted, the 10000ms variant works in a fundamentally different way from the other tests, but still ...

Equally surprising to me was that the "warmed up" JS example operates at almost the same speed as the C# example (~300ms vs ~280ms). And the "best performance" examples for both were even closer in runtime.

Just goes to show how insanely well optimized V8 is, as a JS engine. Say what you will about the bloat of Node.js projects (you'd be right, anyway), but the fact that the same JS engine in your browser is also powering some web server somewhere is pretty mind-blowing stuff.

17

u/Retsam19 Apr 17 '19 edited Apr 17 '19

Well, yeah, because most JS frameworks aren't writing about how to sum the squares of 32 million floating point values.

Most JS use-cases are about front-end UIs which both generally don't include huge data calculations, and are generally IO-bound, not CPU-bound, anyway: the performance bottlenecks front-end UIs almost always come from network requests or DOM operations, and not from the speed of list manipulation operations.

In the vast majority of cases, the readability/maintainability concerns are more important than the performance implications, which is why I prefer .map/.reduce and other higher-order friends, over simple for loops (or .forEach loops).

13

u/[deleted] Apr 17 '19

Most JS use-cases are about front-end UIs which both generally don't include huge data calculations

JS and the browser is increasingly used as an app platform. You can record audio and even video. I myself wrote some code recently to perform RMS audio normalization on the client, which involved doing the sum of squares of quite a large number floating point vlaues (don't think it was 32 million though).

22

u/oridb Apr 17 '19

and are generally IO-bound, not CPU-bound, anyway:

My laptop fans would beg to differ.

10

u/Retsam19 Apr 17 '19

I'm quite sure it's not because your websites are iterating over 32 million floating point numbers inefficiently. A lot of it is DOM rendering - reflows, expensive CSS animations, etc - which, yeah, is CPU-based, but from the perspective of Javascript code, it's IO.

AFAIK, it's very rarely the issue that the JS thread is overloaded.

8

u/[deleted] Apr 18 '19

most JS use-cases are about front-end UIs which both generally don't include huge data calculations, and are generally IO-bound, not CPU-bound

UI is CPU bound.

Most JS frameworks do a lot of CPU bound stuff like diffing large data structures and mutating the DOM.

2

u/Retsam19 Apr 18 '19

Yeah, I clarified a bit on a different part of the thread:

A lot of it is DOM rendering - reflows, expensive CSS animations, etc - which, yeah, is CPU-based, but from the perspective of Javascript code, it's IO.

From the machine's perspective, yeah, it's CPU work, but my original point is that the problem is pretty much never that the JS thread is overloaded, the efficiency of array iteration is generally not the issue.

6

u/[deleted] Apr 18 '19

DOM manipulation is not IO.

Honestly I'm just sick and tired of people writing obviously slow code and then justifying it by saying "but my application is IO bound not CPU bound".

19

u/jcelerier Apr 17 '19

In the vast majority of cases, the readability/maintainability concerns are more important than the performance implications, which is why I prefer .map/.reduce and other higher-order friends, over simple for loops (or .forEach loops).

so why the hell are every friggin website on earth running at 10fps !

6

u/VRtinker Apr 17 '19

Assuming it is a genuine question and not a rhetorical one, here are a few reasons:

  1. Because even a single synchronous piece of code can slow down the main thread and stall the whole UI. E.g., just synchronously reading or writing document.cookie in an onscroll handler might slow down UI.

  2. Because you might have weird CSS (or JS changing CSS) that forces redraw when nothing changes on the page. Try opening Console > Rendering and select "Paint flashing". If you see a lot of stuff being redrawn (flashed) when it should not change, try simplifying your styles.

18

u/Retsam19 Apr 17 '19

the performance bottlenecks front-end UIs almost always come from network requests or DOM operations, and not from the speed of list manipulation operations.

5

u/[deleted] Apr 18 '19

Then don't do so many DOM operations.

4

u/Retsam19 Apr 18 '19

Well, yeah, that's like saying the secret to winning basketball games is to score more points. Obvious, but doing it is the hard part.

→ More replies (2)

9

u/lelanthran Apr 17 '19

In the vast majority of cases, the readability/maintainability concerns are more important than the performance implications, which is why I prefer .map/.reduce and other higher-order friends, over simple for loops (or .forEach loops).

You really think that this:

  var sum = values.map(x => x*x).
             reduce( (total,num,index,array) => total+num,0.0);

is more readable than this:

    var sum = 0.0;
    for (var i = 0; i < values.length;i++){
        var x = values[i];
        sum += x*x;
    }

24

u/Retsam19 Apr 17 '19

I think their reduce code is badly written, but to the general point, yes, I think this is clearer:

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

Is it pretty much a moot point for this incredibly simple use-case? Yes, but as the complexity grows, the benefits of the functional style really show, compared to large for loop.

7

u/m50d Apr 18 '19

Yes I do. Don't you? No extra counter variable to keep track of, no generalized for loop that could be doing anything, no in-place mutation of variables. In fact the only way to read the second (longer) code quickly is to recognize that it's a particular common pattern - wouldn't it be better to actually give that pattern a name and pull out the common parts?

1

u/lelanthran Apr 18 '19

Yes I do. Don't you?

What I think is irrelevant. What I've seen is that most programmers don't parse the more complex expression as easily as the simpler one.

No extra counter variable to keep track of, no generalized for loop that could be doing anything, no in-place mutation of variables. I

No, but extra keywords to recognise (map, then reduce), extra concepts to learn (map/reduce in particular, multiple compound expressions), anonymous functions if you want to do anything non-trivial.

I don't see the first form as being harder to maintain.

3

u/m50d Apr 18 '19

What I've seen is that most programmers don't parse the more complex expression as easily as the simpler one.

I'd agree with that statement, but I suspect you're claiming that the more complex one is "simpler".

extra keywords to recognise (map, then reduce),

Not keywords, just functions. They behave like normal functions, and usually you can read their source code if you want to know what they do.

extra concepts to learn (map/reduce in particular, multiple compound expressions), anonymous functions if you want to do anything non-trivial.

I don't know what you're calling "multiple compound expressions". Both implementations use + and * operators with their normal mathematical meaning and a literal 0.0. In addition to that the map/reduce version only requires the reader to understand a normal expression made of function calls and an anonymous function (both very general constructs that you use again and again on a large codebase). The imperative version requires understanding a mutable variable, the for keyword, the ++ and += operators which are not standard mathematical things, the [i] operator which is not standard anywhere else either, and a {} block of ;-separated statements. In addition to just being a much bigger pile of concepts, half those things are special-case dedicated operators that can't be reused for much else (e.g. [i] is only for arrays, ++ is only for numbers).

→ More replies (1)

14

u/[deleted] Apr 18 '19

They're both about as readable to each other as me.

You realise you didn't come out of the womb being able to read for loops, right? Just because it's typically taught to us first does not make it inherently more readable. I know basic functional constructs, so I know what map and reduce do.

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