Re:Don’t assume that safety comes for free: a Swift case study
by iainmerrick on Tuesday December 06, 2016 @03:29PM
(#13118013)
Good point! You're right, it is a little surprising that reduce() adds any overhead at all in this trivial example.
It's interesting that Swift can't seem to fully eliminate that abstraction overhead when runtime checks are enabled -- maybe there's something other than overflow checks that's getting in the way?
The author hints that the abstraction cost does vanish when checks are disabled, but doesn't bother showing any numbers.
Re:Don’t assume that safety comes for free: a Swift case study
by jckarter on Tuesday December 06, 2016 @04:15PM
(#13118405)
Looking at the generated code, we have a couple issues that prevent full optimization. One of them I already knew about (https://bugs.swift.org/browse/SR-2926) -- as a debugging aid, we guard every trap we emit with the equivalent of an `asm volatile("")` barrier, because LLVM will otherwise happily fold all the traps together into one trap. We really want every trap to have a distinct address so that the debugger can map that trap back to the source code that emitted it, but the asm barrier prevents other optimizations as well. As for `reduce`, it looks like the compiler does inline away the closure and turn the inner loop into what you would expect, but for some reason there's more pre-matter validation of the array than there is with a for loop. That's a bug; by all means, reduce is intended to optimize the same.
It depends! Consider these three functions, in Rust: https://gist.github.com/steveklabnik/da82b51f9dbedd532192492...
One uses a loop, one uses fold with a closure, one uses point-free style. On my machine, summing a vector of a million fives gives
(there is some variance here between runs, sometimes the +/- for each changes a bit.)Cargo's bench profile doesn't use debug assertions, and hence, no overflow checks by default. Let's turn them on:
Looks like they're being eliminated by LLVM anyway.Using godbolt, both the loop and the fold versions (I didn't bother to look at pointfree) are both getting vectorized, and while they're not _exactly_ identical, they're quite similar.
(disclaimer: YMMV, I might have made a mistake, always inspect assembly for your situation, etc)