@noescape attribute in Swift 1.2

后端 未结 3 1925
生来不讨喜
生来不讨喜 2020-12-04 07:03

There is a new attribute in Swift 1.2 with closure parameters in functions, and as the documentation says:

This indicates that the parameter is only

3条回答
  •  无人及你
    2020-12-04 07:21

    (In reference to Michael Gray's answer above.)

    Not sure if this is specifically documented for Swift, or if even the Swift compiler takes full advantage of it. But it's standard compiler design to allocate storage for an instance on the stack if the compiler knows the function being called will not attempt to store a pointer to that instance in the heap, and issue a compile-time error if the function attempts to do so.

    This is particularly beneficial when passing non-scalar value types (like enums, structs, closures) because copying them is potentially much more expensive than simply passing a pointer to the stack. Allocating the instance is also significantly less expensive (one instruction versus calling malloc()). So it's a double-win if the compiler can make this optimization.

    Again, whether or not a given version of the Swift compiler actually does would have to be stated by the Swift team, or you'd have to read the source code when they open-source it. From the quote above about "minor optimization", it sounds like either it doesn't, or the Swift team considers it "minor". I would consider it a significant optimization.

    Presumably the attribute is there so that (at least in the future) the compiler will be able to perform this optimization.

提交回复
热议问题