by saagarjha · 5y ago · 0 comments
let vC = [Float](repeating: 1, count: 4)
func unidiomatic() -> Float {
var vA = [Float](repeating: 0, count: 4)
let vB = [1, 2, 3, 4] as [Float]
var tempA: Float = 0.0
for _ in 0..<1000 {
for i in 0...3 {
tempA += vA[i] * vB[i]
}
for i in 0...3 {
vA[i] = vA[i] + vC[i]
}
}
return tempA
}
func idiomatic() -> Float {
var vA = [Float](repeating: 0, count: 4)
let vB = [1, 2, 3, 4] as [Float]
var tempA: Float = 0.0
for _ in 0..<1000 {
tempA = zip(vA, vB).map(*).reduce(0, +)
for (index, value) in vA.enumerated() {
vA[index] = value + vC[index]
}
}
return tempA
}
When compiled with optimizations (it's unclear if the author did this?), the "idiomatic" code here is indeed much worse. It's easy to fix the worst of that by working on a lazy sequence, i.e. tempA = zip(vA, vB).lazy.map(*).reduce(0, +)
which will save on an extra array allocation and instead run the sum "in place" (in this case, vB is recognized as a constant and in both cases and distributed accordingly). Unfortunately there is still a small amount of overhead because zip doesn't know that the arrays are of the same length, so the compiler inserts some extra bounds checks; also, the second loop gets transformed into what is essentially temp = __swift_intrisic_move(vA)
for (index, value) in vA.enumerated() {
temp[index] = value + vC[index]
}
vA = __swift_intrisic_move(temp)
but this should ideally bring the performance of the two much closer.Also, just to be entirely clear, an example like this (once I “fixed” it) is probably the best Swift can reasonably expect to get, since it hits all the hardcoded semantic hints that Array has been annotated with. It actually does get quite close to the unidiomatic version; save for some extra bounds checks from the zip and a dubious double move, it’s basically done as well as it could with constant propagation and inlining. More complex examples are unlikely to fare as well.
(This can't happen automatically because the default semantics generally involve a panic or exception to be triggered when the check fails; there's no way to optimize this further.)
Transforming from reduce to map-reduce is usually very trivial, but has to be kept in mind
```
swiftc -emit-sil ...
```
Then if that doesn't workout, then try to dump LLVM IR:
```
swiftc -emit-ir ...
```
Both compiler flags should be available in out-of-box Swift compiler.