3 ms·
The Duff's device is a low level optimization that can even hurt modern processors due to branch prediction. It's a niche trick from the olden days. It is very
by cosarara 7y ago
The Duff's device is a low level optimization that can even hurt modern processors due to branch prediction. It's a niche trick from the olden days.
It is very strange on first sight that a[index] is same as index[a], but you will never see the second one used in practice. When you are learning, you can write your code using normal array access syntax and solve problems. And then, you can learn to use pointers and deref them. And then one day you might realize that x[y] is *(x+y) and thus y[x] and that it looks funny. But that will be a long time after writing `wc`.
- heavenlyblue 7y agoDoes that even work in C when sizeof x[i] > 1?
- cosarara 7y agoYes, it does. You can try it yourself with this code example: https://repl.it/repls/PutridUselessComputer https://repl.it/repls/PutridUselessComputer
- heavenlyblue 7y agoIt still made more sense to me more than foldl vd foldl’.
- sifar 7y agoHow would this work for unaligned accesses - which index would very likely be. A neat way to look at things nevertheless, thanks.
- cosarara 7y agoThe alignment doesn't matter. `index` is not an offset in bytes, it's just an index, a number. The position in memory of the variable also doesn't matter as it is not used, only the value. `index[arr]` means `*(index + arr)`. Which is exactly the same thing as arr[index], no matter how you look at it. The type of arr is taken into account for pointer arithmetic. Whatever works with `arr[index]` will also work with `index[arr]`. You can also use a constant, for example `2[arr]`. Damn I hate HN formatting.
- sifar 7y agoyes, I realized this after asking the question :).I must admit I never thought it in this way. Thinking more about this, this might fail if the compiler uses post-incrementing load/stores which update the pointer addresses too. Or will it not use them if I am using index[arr] ? Lets say the load/store updates the pointer too. So after first execution, ptr will index+arr in both cases, but during the next iteration , the former will be ptr[index] while the latter will be ptr[arr].
- tom_mellior 7y agoUnless you try hard to provoke one, there is no unaligned access. Adding a pointer and an integer in C always displaces the pointer by elements, not by bytes. So if p is a pointer to some type T and is aligned, then p + 1 will be aligned as well. You need to cast to another pointer type, do arithmetic on that, then cast back to produce an unaligned access.