3 ms·
You know how GCC compiles mutable C code? It converts it into immutable SSA form, optimizes it in this form, and it's only at the register allocation stage that
by lmm 12y ago
You know how GCC compiles mutable C code? It converts it into immutable SSA form, optimizes it in this form, and it's only at the register allocation stage that things become mutable again - if two different reassignments of your variable end up compiling to the same register, at some level it's only coincidence that they did so. So unless you're doing handwritten assembly, you're already relying on the compiler's ability to optimize away redundant copies.
Why does GCC do it like this? For the same reason FP systems do: because it's easier to reason about immutable values, and easier to optimize things you can reason about. In general the closer we can get to telling the compiler our intent, the better the performance we should ultimately be able to unlock. If we tell the compiler to create a loop variable and increment it, it has to do that (or at least, has to simulate the effects of doing that). If we just tell the compiler to apply this function to every element of this list, it has the option of being smarter about it.
There's an argument that this will be much more important as the world becomes ever more multicore. In a multicore environment immutable values become much easier to work with because they can be safely copied around; with mutable variables your program can end up spending more time on synchronization overhead than actually doing things. I'm not sure how much I believe this, but it could explain the recent rise in popularity of functional languages.
- ansible 12y agoThe world is already pretty multi-core. I was recently spec'ing out a high-end system for simulation work. You can now get Intel Xeons with up to 14 cores now, and soon 18. Talking about 36 high-end cores (dual-socket system) used to be the realm of Sun E10Ks and other very expensive systems. This is amazing to me.
- the_why_of_y 12y agoIndeed, here's an interesting paper arguing this point: SSA is Functional Programming. Andrew W. Appel. http://www.cs.princeton.edu/~appel/papers/ssafun.ps http://www.cs.princeton.edu/~appel/papers/ssafun.ps What is omitted there however is a discussion of pointer parameters and call-by-reference; probably these cannot be treated in the same way as local variables since they point to a fixed address passed in by the caller, so at that point SSA can't be functional, unless I'm missing something.