Optimizations of declarative programming

Hello community,
does Swift compiler translates the code from case A in efficient way into machine code?

case A

array
  .compactMap { $0 as? UIView }
  .forEach {
    // do some operation
  }

or for performance reasons better to write the code in the next way?

case B

array
  .compactMap { 
    guard let value = $0 as? UIView else { return nil }

    // do some operation
  }

Examples are very trivial and with clear input, and of course we always can look at a case, and apply the way which depends on the context, and prefer readability over pre-optimization, where we don't expect millions of values, which in that case we would use imperative approach for a processing.

Could you tell in details about Swift compiler, does it handle such cases or maybe it in plans to cover such cases in a future?

1 Like

While some rough generalizations can be made, I'd be cautious about using heuristics other than "what is the most readable" here. That said, I've recently discovered godbolt and it is a really fun way to introspect what happens with specific code samples and specific compiler versions (I think Xcode may have a similar feature, but less easy to share). Note that the compiler makes no guarantees that certain things currently optimized one way will be optimized the same way in the future.

Thanks for the shared link, George, and agree with your point about no guarantees.

It would be very interesting to hear opinion from developers of Swift compiler.

What you're describing is called (stream) fusion. In certain cases, the Swift compiler can coalesce multiple loops into the same loop. However, there are no general guarantees around when this will/will not expected to happen, and there is no programmer controlled way of making sure the compiler does fusion in a particular way. That said, if you use LazySequence, I believe that you should give you the desired result (no additional intermediate array allocation), except that you need to have an extra step of converting the lazy sequence to an array at the end.

4 Likes
Terms of Service

Privacy Policy

Cookie Policy