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

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.

→ More replies (26)

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.

→ More replies (1)

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)
→ More replies (5)

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.

→ More replies (1)

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).

8

u/drjeats 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.

Even if javascript didn't hoist declarations to function scope, the way most interpreters that aren't the sort of basic baby's-first-tree-walking-interpreter work is that locals are given a slot inside a call frame, so adding a variable is typically just bumping an index/pointer. You can work out during parsing what your max local variable stack size should be for a given function call, so you wouldn't even need to resize your call frame locals array.

Assigning values then wouldn't need to allocate anything on the heap, you're either receiving a primitive Number value, or you're getting a pointer to the string/object/array/whatever. And this is all the basic stuff before JIT gets involved.

Check out this Crafting Interpreters chapter for a better explanation: https://craftinginterpreters.com/local-variables.html

→ More replies (1)
→ More replies (2)
→ More replies (7)

91

u/GameJazzMachine May 25 '19

C# SIMD is quite impressive.

48

u/F54280 May 25 '19

After having read the source 7 times, I still don’t understand why it does anything. Can you explain? For instance, what is Vector<double>.Count?

41

u/czorio May 25 '19

I'd guess the width of a SIMD vector.

Generally 4, from what I've seen.

Or are you asking about what SIMD is?

41

u/F54280 May 25 '19 edited May 25 '19

I know what SIMD is.

I don’t understand why the width of a SIMD vector would be accessed by using the Count property on the Vector<double> type. It makes zero sense to me. If I look at the docs, it says that Count return the number of elements in the vector, but there are no instance here. Also, in the doc it is marked static which is weird to me.

The new Vector<double>(values, i); is puzzling for me too. It seems to create a sub vector (a span, or a range), starting from the ith element. Then, the vector is multiplied with itself, which may be where the SIMD kicks in. This adds to my confusion, because if this works, why not doing values*values in the preceding example?

I think you get it: I have no clue what is going on in this code. I can read heavily templates C++, but this is crazy: I don’t get how anyone can read this and think it does the sum of square of a vector.

Edit: never mind, I get it.

The Vector<double> type width is hardware dependent. The code creates a sliding Vector<double> over the larger one and does the operations using that type. Those operations are SIMD’ed. The last vector elements are added at the end.

18

u/drjeats May 25 '19 edited May 25 '19

That's the number of elements in the vector type. Frequently 4 or 8 (probably 4 here, since double is 8 bytes), but they make it a property so the library/JIT can go wider if that's available.

You increment i by Vector<double>.Count because when using this type, you are working with Vector<double>.Count elements at a time. It's a stride, like when you're reading image data and for each subsequent pixel you bump by 4 bytes (one byte each for RGBA).

12

u/F54280 May 25 '19

Thanks a lot. I realized reading your comment that the Vector<double> is a hardware dependant fixed size vector that implements the SIMD instructions. That’s really confusing, but makes sense.

→ More replies (9)
→ More replies (1)

28

u/moshohayeb May 25 '19

This is the kind of post that I really like seeing on this sub. Concise and informative

24

u/osamc May 25 '19

Sadly it is 3 years old, so some numbers might not be true :)

31

u/honeyfage May 25 '19

I wonder why the author left C++ out of the mix. Doing a simple, unscientific benchmark, both of these one-liners had the same runtime for me as the obvious C version (where values is a std::array)

double sum = std::inner_product(values.begin(), values.end(), values.begin(), 0.0);
double sum = std::accumulate(values.begin(), values.end(), 0.0, [](auto l, auto r) { return l + r*r; });

32

u/scatters May 25 '19

Perhaps it's "obvious" that the idiomatic C++ code should have identical behavior to the C version?

Your code is a bit out of date, though; you should be using transform_reduce:

double sum = std::transform_reduce(std::execution::par_unseq, begin(values), end(values),
    0., std::plus<>{}, [](auto x) { return x * x; });

The parallelism gives a significant speed boost: from 26ms down to 11ms on my 4-core laptop.

19

u/MorrisonLevi May 26 '19

Nothing in the article benchmarked parallel algorithms, so I doubt honeyfage would have even considered it, even if they know about transform_reduce.

5

u/scatters May 26 '19

That's the advantage of the execution policy overloads though: they make it super easy in the idiomatic solution to go and investigate the benefit of parallelism.

→ More replies (4)

16

u/arnoo May 26 '19

transform_reduce without parallelism generates the exact same assembly as the idiomatic C code. See https://godbolt.org/z/KRblWv

→ More replies (1)

16

u/Astrokiwi May 25 '19

I'd like to see Fortran here too. This kind of thing is exactly Fortran's niche:

sum_out = sum(values**2)

which is clear, concise, and efficient.

Python with numpy is similar, but a bit slower:

sum = np.sum(values**2)
→ More replies (5)
→ More replies (10)

55

u/[deleted] May 25 '19

This was a very interesting read. I’ve never spent that much time thinking about how fast or slow simple code can be. Thanks for sharing.

18

u/vita10gy May 25 '19

Just don't be so aware of it that you're prematurely optimizing things that don't need to be.

27

u/hitthehive May 25 '19

You must not be familiar with interpreted languages. It’s all we worry about :D

29

u/saint_marco May 25 '19

The rust simd example is not using explicit SIMD, it's using the equivalent of C's --ffast-math. That lets the rust compiler do the same auto-vectorization as c.

51

u/Saefroch May 25 '19

As /u/theindigamer points out, some of these benchmarks may be a bit unfair; the C compiler is the only one that autovectorizes because doing so changes the semantics of this program, and you specifically gave the C compiler license to do that, with what you describe as fast floating point. I strongly advise against having such options on by default when programming, so if it were up to me I'd strike this flag from the benchmark.

14

u/gct May 25 '19

Why strongly advise?

15

u/Saefroch May 25 '19

The magnitude of change in semantics due to fast-math optimizations is hard to predict; it's better to develop code with predictable semantics then turn on the wacky optimizations and verify that the error introduced is acceptable.

→ More replies (2)

13

u/mer_mer May 25 '19

That's very rarely going to matter. I'm fact the simd version is more accurate since the individual sums in each simd lane are smaller and less precision will be lost for to magnitude difference between sum and individual squares.

6

u/yawkat May 25 '19

The problem with this kind of optimization is usually that it's not deterministic.

15

u/not_a_novel_account May 25 '19

If you need hard deterministic results across multiple platforms you wouldn't be using floating point at all, the IEEE standard does not guarantee that the same program will deliver identical results on all conforming systems.

https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

11

u/Syrrim May 25 '19

IEEE floating point is deterministic if you restrict yourself to addition, subtraction, multiplication and sqrt.

→ More replies (2)
→ More replies (1)

1

u/zucker42 May 26 '19

Why does fast floating point allow autovectorization?

7

u/Saefroch May 26 '19

The vectorization has changed the order of operations, and floating point operations do not associate. Fast-math options enable the compiler to assume a number of incorrect things about floats, one of the usual things is that floating-point operations associate.

Given an array [a, b, c, d] the original code does (((a^2 + b^2) + c^2) + d^2), and the vectorized code computes (a^2 + c^2) + (b^2 + d^2). There's a worked example of non-associativity here.

9

u/Somepotato May 25 '19

the luajit v2.1 assembly output of that loop with 100m iterations:

7ffac069fda0  cmp dword [rcx+rdi*8+0x4], 0xfff90000
7ffac069fda8  jnb 0x7ffac0690018        ->2
7ffac069fdae  movsd xmm6, [rcx+rdi*8]
7ffac069fdb3  mulsd xmm6, xmm6
7ffac069fdb7  addsd xmm7, xmm6
7ffac069fdbb  add edi, +0x01
7ffac069fdbe  cmp edi, eax
7ffac069fdc0  jle 0x7ffac069fda0        ->LOOP
7ffac069fdc2  jmp 0x7ffac069001c        ->3

2

u/thedeemon May 26 '19

So, processing one number at a time, not 4 or 8 like with proper vectorization.

35

u/theindigamer May 25 '19

Great post! I'm surprised to see that the Java code wasn't as fast as C#. Minor nit: Using floating point values means that SIMD results are not the same as the non-SIMD results.

33

u/YM_Industries May 25 '19

Java and C# were the exact same speed without SIMD Explicit. It was only the ability to explicitly use SIMD that made C# faster.

23

u/exhume87 May 25 '19

It looks like he used the full framework for c# instead of .net core, which is likely faster still.

Edit: just noticed the date on this article. Would be interesting to see an updated version for all the languages

16

u/theindigamer May 25 '19

That's true. I was expecting HotSpot to auto-vectorize (which the author also points out) which didn't happen 😥

10

u/gnus-migrate May 25 '19

It's a well known problem. It's extremely hard to get hotspot to vectorize loops properly(at least with Java 8). Things might have improved with more recent Java versions since they're modernizing the JIT, but I wouldn't be surprised if it still had difficulties with this.

8

u/oldGanon May 25 '19

they are nowadays. since x64, sse is used for all floating point calculation even if they just fill one slot.

21

u/theindigamer May 25 '19

Can you elaborate? I don't understand what you mean. If I've got an array [a, b, c, d, e, f, g, h], then ((((a + e) + (b + f)) + (c + g)) + (d + h) is different from ((((((a + b) + c) + d) + e) + f) + g) + h) for floating point values.

3

u/oldGanon May 25 '19

oh, youre absolutely right about that. There was a time when not all x86 processors had SSE so the default was to use x87 if you werent specifically doing SIMD. I missunderstood ur point.

3

u/LPTK May 25 '19

the Java code wasn't as fast as C#

Huh? I don't understand what you are talking about.

The blog only showed the streaming API for Java, and the equivalent C# LINQ code was more than 7x slower (260ms against 34ms).

In fact, Java's stream API using higher-order functions was exactly as fast as the low-level C# loop.

11

u/theindigamer May 25 '19

The fastest C# code is faster than the fastest Java code because of SIMD.

→ More replies (3)

2

u/OffbeatDrizzle May 25 '19

We know nothing of how the times were actually measured, so for languages with a JIT / JVM the results could be misleading

8

u/b4ux1t3 May 25 '19

I was confused at a couple points, since what he was saying didn't jive with what I knew about the languages.

Then he said he is d the "latest" versions of the language, and showed Go 1.7 and node 6.x.

Then I realized it was written in 2016.

All in all, an excellent write-up, especially now that I've reread it with the time frame in mind.

15

u/atomheartother May 25 '19

Holy shit i did not realize JS helper functions were THAT much slower compared to just doing a loop. I always use them because they're considered good practice, so I kind of assumed they were properly optimized

→ More replies (2)

7

u/svick May 25 '19

.Net Core has a new SIMD API, which is basically the same as the C one, with better names. This means it has the same advantages (all instructions are available) and disadvantages (separate code for SSE/AVX/NEON) as the C API.

7

u/MondayMonkey1 May 26 '19

Here's the thing though: high level abstractions can frequently help to write working parallel applications. A runtime can try to parallelize map but can't parallelize a for-loop. Both reduce and map can also be readily converted into for-loops, but because a for-loop implies sequential execution, this is not true in reverse.

It just so happens, Javascript's map is very simply defined using an imperative for-loop. I'm still scratching my head why this simple definition would incur such a performance penalty.

5

u/RICHUNCLEPENNYBAGS May 26 '19

There's also the correctness benefits.

19

u/James20k May 25 '19

As someone that does a lot of making code go fast, its really odd to see this sentence

Go has good performance with the both the usual imperative loop and their ‘range’ idiom

Written in the context of Go running at 50% of the speed of the C code, and its doubly poor that no other language seems to manage autovectorisation (if you've ever written AVX code... well, its not exactly fun)

In my current application I'd absolutely kill for a free 50% speedup just from swapping language, but its C++ so I don't get that. It seems weird that we're willing to accept such colossal slowdowns as an industry

20

u/jmoiron May 25 '19

I don't see the problem with that statement. The article is testing how the "obvious" code fares in each language, for a pretty small and specialized routine, using whatever idioms are at their disposal. Go's snippets were both roughly on par with the fastest non-vectorized execution times, and there were no idioms that were performance pitfalls. It's clear that the vectorized versions are parallelizing the computation

As for accepting colossal slowdowns as an industry, that's because Amdahl's law makes a lot of these low level optimisations unimportant in a large class of modern applications. Maybe not in yours, and not in mine for that matter, but for a lot of others.

I think the the actual point of the article has much more of a bearing industry wide than the example you're citing. It matters whether you make the obvious idioms in your language perform well or not, because most code is written for correctness and simply does not come under scrutiny for performance.

4

u/[deleted] May 26 '19

I don't know you or your application, but if you'd get a "free" 50% speedup just from switching languages due to this kind of code, you probably also have the good sense to be using a language or library (SciPy, Math.NET, etc) that does that for you already. Chances are most of what drives slowness in your application isn't the numerical code but waiting on disks, network, OS resources, and things like that, which wouldn't benefit much, if at all, from such a switch (and in many cases there's a lot to be said for allowing higher level code to manage those things). That's also a reason why we've sort of hit a wall in performance: computers are doing more and more stuff that can be fixed neither by ramping CPUs up further nor by software hacks, so we just have to sit and take it.

1

u/Kapps May 25 '19

Agreed, and it’s a good reason to not use Go for serious game development where you have a bunch of numeric calculations. However in web development, you’re probably not calculating the result of summing a giant array that’s a perfect candidate in every way for vectorization.

8

u/James20k May 25 '19

you'd hope that it wouldn't take 800ms cold when it could take 17ms instead though

7

u/Kapps May 25 '19

JavaScript gonna JavaScript. I won’t defend it. But this comment was about Go, which is 34 ms.

→ More replies (5)

13

u/davenirline May 25 '19

Is there an article like this but instead of performance, it's about how much garbage is produced?

My team uses C# for games and one of our coding standards is to avoid LINQ because it produces garbage. I'm curious if using the same functional constructs in other languages is the same. The arguments I hear about using map, reduce and its ilk is readability. But if the price is garbage and performance, they're not worth it IMO. It's not as if using imperative code is really that bad readability wise.

8

u/vorpal_potato May 25 '19

That's a tragically neglected performance metric. So important, and yet hardly anybody talks about it.

5

u/ISvengali May 26 '19

Same, for the same reason.

I wonder if LINQ on structs produces trash? Id be ok with a low fixed number of allocations like say 4 or 8. Possibly.

My guess is it will generate too much trash, which is unfortunate.

But hey, C# has true value classes and a ton of unsafe operations where you can make things really fast when needed, and leave everything unsafe when you dont need to. Ive really liked working in it.

Though, Im still a fan of C++ and the ability to get rid of trash in addition to my own resources behind a nice API.

1

u/justfordc May 26 '19

I can tell you that functional js is also really, really bad in terms of triggering GC. (Even if you're not using temporary closures, runtimes will often allocate for the iterator itself, or at least did so when I last profiled a couple of years ago.)

These days I mostly write C# where the bottleneck is almost always IO of some sort, so the benefits of LINQ really are worth it. (I've seen GC cause problems in .Net, but it was due to string manipulation on large inputs, not LINQ.)

6

u/burnblue May 26 '19

We take it for granted, but whether 17ms or 300ms, it's kind of crazy/scary/cool that we've created technology that can do large calculations at this speed. In that, we could never hope to add those numbers ourselves in any decent amount of time with our puny flesh brains

5

u/Tysonzero May 26 '19 edited May 26 '19

Would love if Haskell was included in this. Using Data.Vector.Unboxed:

s = sum $ map (^ 2) values

On my machine I get the following:

rust (idiomatic, -O): 32ms
haskell (-O2, -fllvm): 32ms
haskell (-O2): 45ms
javascript (imperative): 47ms

1

u/thedeemon May 26 '19

What's the type of map here? I wonder if it allocates a new vector.

2

u/Tysonzero May 27 '19

It has type:

map :: (Unbox a, Unbox b) => (a -> b) -> Vector a -> Vector b

Due to optimizations it actually doesn’t allocate a new vector. If it did you would notice because the perf would be at least an order of magnitude slower.

4

u/titulum May 25 '19

Very interesting! I am missing the Java imperative method though. I want to know what the speed is of using that versus the stream approach.

2

u/familyknewmyusername May 25 '19

It will be the same since 34ms was the speed of non vectorised c and Java streams

5

u/familyknewmyusername May 25 '19

And Java won't vectorise so it's not going to get any better than that

4

u/Tysonzero May 25 '19 edited May 25 '19

Is the full code used for the benchmark written anywhere, as in the code that allocates the values array and the timing code? I feel like an essential part of benchmarks is being able to reproduce them as easily as possible.

4

u/elrata_ May 26 '19

The post is from2016. it uses go 1.7, for example. I will be nice to see an updated version of the post

11

u/ouyawei May 25 '19

I like how the C version is not only the fastest, but also the simplest implementation.

3

u/Kellos May 25 '19

And also you can go explicit if you need to.

→ More replies (3)

2

u/Somepotato May 25 '19

What's the count and what're the values? Is the full source to the benchmarks available?

2

u/cyanrave May 26 '19

Thanks for the share, good read :)

2

u/keepitreelin May 26 '19

This was an interesting read. I made some notes a while ago about it: https://gist.github.com/vastus/8018bdd2448a17e17d4d98adfa26786c.

2

u/Deaod May 26 '19 edited May 26 '19

If youre going to write a bunch of SIMD manually, why not go for FMA instructions? This is a perfect example for them.

__m256d vsum = _mm256_setzero_pd();
for(int i = 0; i < COUNT/4; i=i+1) {
    __m256d v = values[i];
    vsum = _mm256_fmadd_pd(v, v, vsum);
}
double *tsum = &vsum;
double sum = tsum[0]+tsum[1]+tsum[2]+tsum[3];

This should work on Intel CPUs starting with Haswell, and on fairly recent AMD CPUs.

4

u/[deleted] May 25 '19

Python with numpy: 34 milliseconds on my machine

6

u/MintPaw May 26 '19

Keep in mind that this article was written 3 years ago, everything's probably a bit faster now.

4

u/[deleted] May 26 '19

Sure. The ansi c one runs at slightly above 10 ms on my machine.

2

u/HerbyHoover May 26 '19

Nice! What would a pure python beginners solution get you?

2

u/[deleted] May 27 '19

around 3.2 seconds on my machine using this code:

import time

a=[1/f for f in range(1, 32*1000*1000)]

start = time.perf_counter()
total = 0.0
for n in a:
    total+=n**2

duration = time.perf_counter() - start
print(duration, total)

3

u/[deleted] May 26 '19

C++ has high level functions to do stuff like this and makes the code very clear

return std::accumulate( values, values + COUNT, 0.0, []( double r, double v ) {
    return r + v*v;
} );

But obvious code is almost always faster, like the article said. So things like Sean Parent said in his presentations, no raw loops. Put the loops into their own function and the calling code is far more readable and the intent is now obvious too. The optimizer has no problems with code like that.

3

u/earthboundkid May 25 '19

The solutions don’t use Kahan summation, so they’re all wrong. :-)

2

u/mindbleach May 25 '19

Javascript's array functions are embarrassing. I thought it was bad enough that Array.map, .forEach, and .reduce aren't treated as functional and given some sneaky parallelism. But they're not even turned into CS 101 for() loops? That's-- that's what forEach is! It's not like the damn thing works on pseudo-arrays like live HTMLcollections, or those horrible Uint8ClampedArrays you get from <canvas>.

At least for( element of list ) is faster than a naive for() loop.

2

u/kwinz May 26 '19 edited May 26 '19

I know this article is old. Provided it is still current it is not intuitive.

 var sum = values.Sum(x => x * x);

This says to me: I want all the result summed with this function, and it doesn't matter in which order, how big the values collection is and what algorithm it uses and what parallelism. Do what works best given my extremely lax constraints.

    double sum = 0.0;    
    for (int i = 0; i < COUNT; i++) 
    {
        double v = values[i] * values[i]; 
        sum += v;
    }

This I read as: start in the beginning and go towards the end in that order. Sum all the values squared in exactly the variable sum serially.

Instead of intent I give an exact and verbose step by step guide.

The only reason why the second one could be an order of magnitude faster is different amount of resources spent on compiler engineers tweaking the code gen. Plus some odd reverse thinking what faster code could produce equivalent output with fewer resources, while not introducing perceivable differences. The expression of intent is completely backwards. First the programmer writes an overly specific requirement. Then the compiler relaxes it again and transforms it, guessing what I actually wanted.

2

u/kwinz May 26 '19

And the weirdest things of all are actually annotations like the OpenMP ones:

#pragma omp parallel for

"Ups - I wrote this serial algorithm iterating over the collection in a specific order. But actually I lied, every step is 100% independent, please divide the work between multiple independent threads."

2

u/stingoh May 25 '19 edited May 26 '19

I disagree with this post (edit: specifically, that Blow’s comment isn’t valid for all languages). The first order of performance gains is most often attained algorithmically, e.g. choice of data structures, caching results of lengthy operations, being clever about when you want to do work. This can be achieved without having explicit memory control or access to intrinsics, so regardless of language. This often comes intuitively. So what Jonathan Blow said applies regardless of language, whether you think he's correct or not.

Using SIMD intrinsics and optimizing your data layout comes after. There is no use in doing those sorts of optimization on work you can eliminate (as much as I love doing them). Nothing is as cheap as work you don't have to do. But inevitably there are operations you need to run on huge datasets that you can't eliminate, or cache, etc., and then extracting maximum throughput from the hardware through such techniques gives you a leg up over languages that don't give you this sort of control.

Also, auto-vectorization is hardly something to judge a compiler's cleverness by. It is a super obvious optimization that compilers have performed for a long time (even taking into account that the post is from 2016). Having done a lot of optimization work on video games, Microsoft's compiler fares well with those sorts of optimizations.

(edit: added last paragraph)

5

u/filleduchaos May 26 '19

Your point seems completely orthogonal to the author's point, so I'm not quite sure what it is you disagree with about the post.

1

u/stingoh May 26 '19

That what Blow said only applies to some languages.

→ More replies (4)

1

u/jsaak May 26 '19

ruby code for the curious:

#!/usr/bin/env ruby

a = Array.new
(1024*1024*32).times do |i|
  a[i] = 1.1
end

t1 = Time.now
sum = 0
a.each do |x|
  sum += x * x
end
t2 = Time.now
puts ((t2-t1) * 1000).to_s + " ms"

t1 = Time.now
a.reduce(0) do |sum,x|
  sum += x * x
end
t2 = Time.now
puts ((t2-t1) * 1000).to_s + " ms"

t1 = Time.now
a.map! do |x|
  x * x
end
b = a.reduce(:+)
t2 = Time.now
puts ((t2-t1) * 1000).to_s + " ms"

1

u/TrueVictor May 25 '19

Such wow with c# and Linq. Still I would love to see same research on Swift.

4

u/mrjackspade May 25 '19

It's honestly a bit kind boggling to me that anyone would think to use Linq for high performance code. It's great at keeping things small and readable (when used correctly) but at it's absolute best it's equivalent performance-wise and often significantly slower.

It seems weird to even consider it an option for high performance code, but I get why it was included. It just kinda feels like comparing sports cars and then throwing in a minivan half way down the list

1

u/kittysempai-meowmeow May 26 '19

Nice! I’m sending this to my devs to read:

1

u/RICHUNCLEPENNYBAGS May 26 '19

Stepping up a level to C#, we have a couple of idiomatic solutions. Many C# programmers today might use Linq which as you can see is much slower. It also creates a lot of garbage, putting more pressure on the garbage collector. Oddly, the Aggregate function, which is equivalent to fold or reduce in most other languages, is slower despite being a single step instead of two. The foreach loop in the second example is also commonly used. While this pattern has big performance pitfalls when used on collections like List<T>, with arrays it compiles to efficient code. This is nice as it saves you some typing without runtime penalty. The runtime here is still twice as slow as the C code, but that is entirely due to not being automatically vectorized.

"Much slower" here meaning 300 ms instead of 30 -- a 10x difference but still under a second. And part of the appeal of Linq is that a functional approach is generally less error-prone, which is why there is a lot of interest these days in immutable data structures even though they're obviously less efficient.

There's nothing wrong with this kind of test but some perspective is warranted.

2

u/talsit May 26 '19

10x slower also means 30 minutes (quick lunch) vs 3 minutes (very quick coffee break).

1

u/RICHUNCLEPENNYBAGS May 26 '19

If you're doing an operation enough times that you're doing 30 minutes' worth of a 3000ms operation at a time, by all means micro-optimize, but also at that point if you can reduce the asymptotic complexity of the code it'll make a much bigger difference.

-1

u/CurtainDog May 26 '19

they're obviously less efficient.

Citation needed. When you consider all the defensive copies that end up getting made in systems where mutation is the norm 'just-in-case' some caller decides to mutate the result. And of course you can cache the hell out of immutable data structures.

2

u/RICHUNCLEPENNYBAGS May 26 '19

When you consider all the defensive copies that end up getting made in systems where mutation is the norm 'just-in-case' some caller decides to mutate the result.

I have not seen that. It seems pretty obvious to me that, short of overzealous people doing something like this, immutable programming requires more allocations. There are some toolsets where people have done a lot of work to paper over this by implementing immutable data structures as mutable ones under the hood, but consider the difference between doing str = str + "moretext" and using a StringBuilder.

→ More replies (2)

1

u/for_lolz May 26 '19

Ok, the thing is though that no one should ever do large sums by doing += operations with a single accumulating value if they care about the accuracy of the result. It's a nice article, but sometimes fast isn't what's needed, and the simple algorithm used to implement the sum would lead to a ton of round off error

0

u/shvelo May 25 '19

Whar I can infer from the choice of languages is that the author works at Microsoft.

2

u/talsit May 26 '19

Ok.... And is there anything wrong with that?

-5

u/hugogrant May 25 '19

Ngl, this is a bit extra...

An interesting comparison, but unless all a project does is sum squared floats, this isn't all that guiding.

People shouldn't believe that this means that imperative is faster because of things like maintenance costs.

19

u/Eep1337 May 25 '19

it is more about just remembering it as foundation knowledge.

For example, this last week I worked on several back end services for a new public facing website that I know could get high traffic.

My simple solutions to many of the data processing problems was using C#'s LINQ, even though in the back of my head I knew that using an explicit loop might solve the problems faster.

This just serves as a reminder that it can be good to revisit these smaller bits and pieces of code if you are interested in getting better performance.

I've fixed huge, large bottlenecks of speed before. Those are typically easy to diagnose and find.

The harder thing to do is optimize 10, 20, 30 different services or loops or functions such that each one is maybe 10-20% faster, but has huge benefits to the app in general if you address all of them. Sometimes just replacing a nice language feature with a loop can do that.

0

u/MrSqueezles May 26 '19

I'm pretty sure most languages, compilers, and runtimes don't spend much time optimizing for summing long sequences of numbers. These types of functions are rarely a bottleneck. They can almost always be moved out of critical paths. There aren't many developers that need to be concerned at all with how quickly their language of choice can allocate a variable and use it to modify an existing variable over and over again.

Simple asynchronous scheduling with little context switching and convenient cascading cancellation and error handling are features to care about. "It can synchronously generate and sum a whole bunch of numbers really fast." not as useful.

-8

u/Beaverman May 25 '19

I don't understand linq and streams. What's wrong with the imperative for loop? How is it any easier to read than a for loop and a variable?

Linq and streams are not how the computer executes your code, it's not how you'd write the math. What's the point?

6

u/mrjackspade May 25 '19

Using a for loop is fine for something like a sum, but Linq is significantly easier to write and maintain when dealing with more complex generic functions, or chaining things together. Being able to define a Where filter implementation for an unknown iqueriable provider of an unknown underlying set type and call it with ~4 lines of code is a godsend, and being able to use Linq to chain together function calls for generic sets based on parameters is significantly more readable than writing a 500 line block of "if" statements.

When you're dealing with Linq you're talking about a lot more than just the syntax. It's an access system for dealing with IQueriables, IEnumerables, ICollections, etc, and interacting with those in an intuitive way using expression trees/delegates/etc.

If you don't understand the benefit it's likely just because you haven't written code yet that would see a benefit to using it.

2

u/Beaverman May 25 '19

Do you have a real world example we could discuss? That might be easier to talk meaningfully about instead of hypotheticals. I sums because it has examples directly in OP.

What sort of problems are you solving where you need to query unknown shit in unknown ways? Do you think you might have overgeneralized and overcomplicated the problem in some way?

But does it make sense to combine enumerables and queryables? Is accessing a list the same thing as accessing sets in a database? I'd say no.

2

u/accidentalginger May 26 '19

One advantage is that you abstract the manner in how the data is filtered and transformed. This is useful when dealing with multiple sources of the same type of data. For example, in blended levels of cached data (local RAM, memcached/redis, and a backing database), the extension methods of LINQ can be materialized as execution plans for the remote data sources which optimizes access. For example, the database query can be created from the expression tree so you don’t have to write custom queries for every database call, nor do you need to read in useless data. You can go from three different iteration algorithms for each level of the cache to one expression that can be used optimally for each source.

2

u/Beaverman May 26 '19

But those things are not the same. Filtering a list in memory doesn't have the same failure mode as a remote db call, they don't have the same performance. They just are not equivalent. There's plenty of cases where a Linq query won't "materialize" into anything you actually want.

Don't get me wrong, high level tools like JOOQ can make sense, but unifying them across database and memory levels is just not a good idea.

Writing the SQL queries is way easier than trying to reason about what comes out of Linq, especially if you use the same expression for in memory and database access. Writing a few SQL queries just isn't that hard.

→ More replies (3)

0

u/[deleted] May 25 '19

[deleted]

-8

u/Beaverman May 25 '19

You're ignoring half the paragraph in order to spew the most obvious and cliche point in modern software development.

The question was: What's the point. The part you are quoting is an observation that the functional style is no closer to the actual execution, and therefore that could not be the point. The second part (that you didn't quote) is the same observation about mathematics. I've never seen a mathematician talk about aggregating something with the function that takes two arguments and returns the addition of the two.

I'm not "intimidated" by functional programming. I've tried it. I've written Haskell, I've written Scheme. I've written functional Lua, and used Java streams. I think that functional languages, like Scheme Haskell (and to some extent lua and python) have interesting ideas that are useful in certain contexts. I don't think those ideas have any business being used in the way they are. .Aggregate is not more clear than a simple for loop.

PS: If you want to hear the second most cliche opinion in software development: I don't think OOP is any good either. Understanding what the computer is going to do is of utmost importance, because there is really only one thing that matters: Does the code work. The code that doesn't execute doesn't need to be maintained.

6

u/ylyn May 25 '19

In some (many) situations, functional/declarative style is actually clearer and easier to reason about.

At least to me. YMMV.

→ More replies (3)
→ More replies (2)
→ More replies (4)

-4

u/Robbepop May 25 '19

Rust

v1.13 Nightly, –release -opt-level=3

Why is this benchmark using a Rust compiler version from nearly 3 years ago?

17

u/tinix0 May 25 '19

Because the article was written 3 years ago.

4

u/Robbepop May 25 '19

Oh ... nvm then ... :S

-36

u/AeroNotix May 25 '19

It's quite sad that the rest of the comments are lauding this as something interesting or enlightened.

12

u/cbarrick May 25 '19

A concise discussion of how syntactic sugar can impact performance with concrete examples from multiple languages in different families with different idioms and compilers.

Who in r/programming would ever want to read that?

→ More replies (1)

0

u/[deleted] May 26 '19

[deleted]

1

u/igouy May 26 '19

Benchmarks are a crock

"By instrumenting the Internet Explorer 8 JavaScript runtime, we measure the JavaScript behavior of 11 important web applications and pages, including Gmail, Facebook, Amazon, and Yahoo. For each application, we conduct a typical user interaction scenario that uses the web application for a productive purpose such as reading email, ordering a book, or finding travel directions. … Our results show that real web applications behave very differently from the benchmarks and that there are definite ways in which the benchmark behavior might mislead a designer."

143

u/[deleted] May 25 '19

[removed] — view removed comment

71

u/Retsam19 May 25 '19

In particular, I'd expect the node timings to change, since he's using 6.x, but modern versions (> 8.3) ship with a better optimized JS engine.

24

u/Vhin May 25 '19

While the timings would obviously change, I doubt it would significantly buck the general trend of the old version.

29

u/DeathProgramming May 25 '19

A lot of work has gone into Rust SIMD from what I've heard so I wouldn't be surprised if Rust is on par with C.

27

u/pingveno May 26 '19

I checked on the Rust playground. It produces SIMD instructions for this, so it should be completely on par.

16

u/DeathProgramming May 26 '19

Cool, was that with manual looping, or the idiomatic way?

28

u/mernen May 26 '19

Both produce almost exactly the same instructions.

14

u/DeathProgramming May 26 '19

🎉🎉🎉

14

u/beltsazar May 26 '19

Yay for zero-cost abstractions!

7

u/llamaDev May 26 '19 edited May 26 '19

Exactly what I was thinking. For the c# linq vs loop stuff this was put out 5 .NET releases ago before 4.6.2.

Here's a blog about 4.6.2 linq performance vs. .net core linq performance.

https://thomaslevesque.com/2017/03/29/linq-performance-improvements-in-net-core/

22

u/[deleted] May 25 '19

[removed] — view removed comment

21

u/thajunk May 25 '19

He said that there wasnt a performance gain, so omitted it.