For case vs compactMap + forEach

Hi,

Me and a friend were discussing the differences between

for case let button as UIButton in subviews {
  // do something with the button
}

and

subviews.lazy.compactMap { $0 as? UIButton }.forEach {
  // Do something with the button
}

at the level of the generated binary code.

Also, what if lazy is omitted?

I know that, generally speaking, without lazy, compactMap will generate intermediate array, then call forEach on the items of this new array.

My questions are:

  1. Does the compiler manage to figure out that those intermediate arrays are not used and produce code without them?
  2. In the lazy case is there any difference in the generated code between for case and lazy.compactMap{}.forEach{}?

Can I get some pointers as to how I can explore the generated code, both the intermediate representation and the optimized binary?

Apart from that, it would be nice if we can hear from someone on the @core-team who can shed some light on how those two constructs defer when generating SIL.

Thanks.

https://swift.godbolt.org/ is a very useful tool for this.

2 Likes
Terms of Service

Privacy Policy

Cookie Policy