r/programming • • Oct 04 '13

What every programmer should know about memory, Part 1

http://lwn.net/Articles/250967/
660 Upvotes

223 comments sorted by

View all comments

150

u/[deleted] Oct 04 '13

I've been a Software Engineer for 13 years and I've never had to use any of this information once.

0

u/[deleted] Oct 04 '13

[deleted]

2

u/Adamsmasher23 Oct 05 '13

I think if you're writing in a language like Java, it's hard to accurately reason about the underlying hardware. But (hopefully) JIT will do most of the optimization that you need.

5

u/seventeenletters Oct 05 '13

You can still be cache-aware in Java. For example by putting an unboxed type in an array you can force locality of the data (see Disruptor for example - this is a big part of their speed boost).

61

u/adrianmonk Oct 04 '13 edited Oct 04 '13

I had a course in college where we studied this sort of stuff. One of our assignments was the teacher gave us a perfectly good looking piece of code that multiplied two matrices, and we had to use our knowledge of caches and the memory bus to make it faster. Rearranging the order in which memory was read and written (so that values would be cached and so that accesses would be sequential) led to dramatic performance increases (2x or 3x, IIRC).

How often does someone need to make an optimization like that? It depends on what you're working on. If you're doing application code that is mainly about business logic, you probably don't need to. If you're doing something more about number crunching or more at the system level, you might be able to make some improvements.

20 or 25 years ago, the prevailing opinion was that every programmer needed to understand how to write in assembly since they'd have to drop to assembly when performance became really important. Optimizing compilers came along and made that unnecessary. But so far, I'm pretty sure no compiler has figured out how to rearrange memory access patterns to optimize for the way the memory hierarchy works.

34

u/maskull Oct 04 '13

Indeed, I was just reading the Doom 3 BFG tech. notes and they spend a good amount of time talking about the rewrites they had to do in order to be more cache-friendly. Optimizing your data structures for locality and the like is something that has actually become more important since the original Doom 3, not less.

20

u/sextagrammaton Oct 04 '13

That's exactly how I wound up finding this article.

6

u/adrianmonk Oct 04 '13

And there was a time when it wasn't important at all. That same 20 or 25 years ago, many desktop processors simply didn't have a cache. For example, a Motorola 68000 had no data cache or instruction cache. (Later the Motorola 68010 came along with a very rudimentary kind of instruction cache that could only be used for "loop mode" and could only hold 2 instructions.)

They didn't have a cache mainly because they didn't need it. Memory ran at basically the same speed as the processor: you could run your processor at 8 MHz and your memory at 8 MHz too. On one of those old processors, main memory ran, in a relative sense, as fast as on-die cache runs today.

Now, processor cores run at 2 or 3 GHz but memory can't go that fast. And the speed of light isn't changing, so cache behavior gets more and more important.

So basically, 20 or 25 years ago, you needed to worry about instruction generation. Over time, that became almost irrelevant, but you started to have to worry about memory access patterns.

→ More replies (10)

4

u/agumonkey Oct 04 '13

Doom had the same 'tricks' for VGA rendering, writing texture colors in certain order matched the underlying machinery.

2

u/skulgnome Oct 04 '13

Since the mid-2000s, nearly all software renderers have rearranged texture images into 4x4 chunks, because in a 8-bpc RGBA format it fits on a single cacheline. This trick increases the cache hit rate in proportion to magnification, i.e. greatly for the densest mip-map, and to between 3/4ths and half the time for smaller sizes.

Really it's just a common example of arranging data according to the use pattern.

→ More replies (2)

5

u/felipec Oct 04 '13

Optimizing compilers came along and made that unnecessary.

It's still necessary in many cases.

3

u/adrianmonk Oct 04 '13

Fair point. It's unnecessary in a lot fewer cases. It used to be that nearly every programmer could potentially need to do it. Now it's probably 1 in 100 or fewer.

2

u/[deleted] Oct 04 '13

Not really. Unless you're writing code that deals with custom hardware. The closest you should get to ASM imo is compiler intrinsics (SSE and the like).

6

u/felipec Oct 04 '13

Wrong. In multimedia and graphics processing people still need to write a lot of assembly code because compilers make tons of mistakes. Same with bitcoin mining and checksuming.

Basically, if you need something CPU-optimized, sooner or later you will need assembly.

2

u/[deleted] Oct 05 '13

I don't know what platforms or compilers you're working on, but on x86 and arm the compilers are great. We (I work someplace you've heard of doing graphics and multimedia) have literally no assembly code. There is no reason why a good optimizing compiler can't generate fast asm, and often it thinks of optimizations that even our best engineers may miss.

You should try racing the compiler sometime on something more complex than a line or two of code. It will most likely win.

Also keep in mind that inserting asm throws off a ton of optimizations because the compiler can't guarantee you're following the c/c++ standards in your asm.

Edit: accidentally submitted to early.

→ More replies (3)
→ More replies (1)
→ More replies (1)

46

u/[deleted] Oct 04 '13

It depends on what you're working on. That information can be quite useless. The title is misleading.

24

u/annodomini Oct 04 '13

It should probably be qualified "what every systems programmer should know about memory."

Generally, on a good platform and when not writing incredibly performance sensitive code, application programmers don't need to worry about this. That's what we have compilers and operating systems and high level languages to abstract away.

But if you need to really get the highest performance out of code (work on games, HPC, big data, etc), or if you're a systems programmer writing those operating systems and compilers that abstract this away for the application developers, then you do need to know it.

→ More replies (6)

7

u/Amadiro Oct 04 '13

It's not necessarily material that you would delve into in the first 13 years of your programmer-existence, unless you aim straight for HPC. It probably took me around 8-12 years or so of programming to start caring around these kind of things in detail. Before that, it was just "yeah, caches exist, let the compiler/CPU take care of it, they'll eventually be infinitely big anyway."

Who would've thunk though, that you don't just suddenly stop learning new stuff, eh?

7

u/willvarfar Oct 04 '13

I'm not sure if you are fortunate or ignorant. Understanding the memory hierarchy is useful even in a JavaScript world, and more-so as we move towards webgl and webcl.

Systems that scale sideways by adding boxes work the same way as scaling sideways on the same box e.g. using more cores. But if you understand how numa works, you can likely refractor your app to fit on a single box anyway...

→ More replies (4)

5

u/Carnagh Oct 04 '13

15 years here, and I'd like somebody to convince me why I should read this material?.. I'd like to talk about leaky abstractions during the exchange.

16

u/xzxzzx Oct 04 '13

Reading this once and retaining a conceptual understanding of things will allow you to make much better guesses at how to make things go fast.

It gets harder to estimate the further from the "metal" you are, because you may not know how things are laid out in memory, but if you know those things too, you can still use the information.

A few things that I can just synthesize from largely conceptual understanding because I'm familiar with this sort of information:

  • Accessing arrays in-order is much faster than doing it "randomly"

  • If you have a number of complicated operations to do on many small objects, it's probably much faster to do all the operations on each object before moving on, rather than doing "passes" for each operation -- unless those operations are going to need to access stuff that isn't going to fit in the CPU cache.

  • If you're doing multithreaded stuff, it's usually much better for each thread to have its own copies of memory to write to rather than sharing it, but having one copy of memory you're only going to read is preferable.

  • It's often much cheaper to calculate something than it is to store it in a big table.

2

u/Carnagh Oct 04 '13

It gets harder to estimate the further from the "metal" you are, because you may not know how things are laid out in memory, but if you know those things too, you can still use the information.

Not only does it become harder to estimate the further you are from the metal, but in much commercial application development it becomes outright dangerous to do so... In many scenarios you do not want your developer making assumptions about the metal they're sat on.

If you have a number of complicated operations to do on many small objects, it's probably much faster to do all the operations on each object before moving on, rather than doing "passes" for each operation -- unless those operations are going to need to access stuff that isn't going to fit in the CPU cache.

Unless you're running in a managed environment and want to ensure your garbage collection can catch up. And as for the CPU cache, that is not something most programmers should be making assumptions about.

Now the other bullet points that you're beginning to boil down are valid, and downright useful to consider across a very wide range of platforms and areas of development... and do not require an intimate knowledge of memory, while also being digestible by a far wider scope of developers.

You right now if you carry on writing and expand upon your points are more useful to 80% of programmers that will ever read this sub than the cited article.

7

u/xzxzzx Oct 04 '13 edited Oct 04 '13

In many scenarios you do not want your developer making assumptions about the metal they're sat on.

And if you understand the concepts involved, you know what things will carry across from one piece of metal to another...

Unless you're running in a managed environment and want to ensure your garbage collection can catch up.

Unless you're using a lot of compound value types, that's not going to be a concern. And if you are... wtf is wrong with you? That's terrible in any number of ways.

The GC will do its thing when it needs to. Why would doing multiple passes improve GC performance? If anything you'd be generating additional objects (edit: from multiple enumerations), putting greater pressure on the GC...

and do not require an intimate knowledge of memory, while also being digestible by a far wider scope of developers.

I don't have an "intimate" knowledge of memory. I couldn't tell you 95%+ of the details from that article. But reading it allowed me to correct a number of things I had wrong in my mental model of how computer memory works (I don't have any examples; I last read that thing ~5 years ago...)

For me at least, understanding why those things are true, seeing examples of how the branch predictor/memory prefetcher in a modern CPU performs, getting some clue of the architecture of all these things--that means I'll actually retain the information, because it's a complete picture, rather than...

"Do this, and that, and also this."

Admittedly, this article has so much detail that I think you could trim it down substantially while still retaining enough detail to explain why each of those bullet points are usually true.

→ More replies (2)

6

u/gefla Oct 04 '13

You shouldn't attempt to completely abstract the real world away. If you try, it'll remind you that it's still there in unexpected ways.

→ More replies (2)
→ More replies (56)