Swift. Is the (Absolutely) Sole Specific Advantage of Unowned Over Weak, Performance

Swift. Is the (absolutely) sole specific advantage of unowned over weak, performance?

I agree with Yannick. Your bold statements are not correct. An unowned reference must be valid for its lifetime. In an -Ounchecked program, failure to maintain this precondition is undefined behavior. I don't mean "it crashes." I mean it is not a well-formed program; it is undefined what it does. A weak reference cannot generate undefined behavior due to its release, even under -Ounchecked.

Using unowned is a statement by the programmer that the reference will be valid over its entire lifetime. That's not even something Type! asserts. ! types just assert that the reference will be valid at the point that it is accessed. That's why you can't test x == nil on an unowned. It is not optional. It's not "optional in disguise" (like Type!). It must always be valid.

Unlike a weak reference, however, an unowned reference is used when the other instance has the same lifetime or a longer lifetime. ... An unowned reference is expected to always have a value. —— [The Swift Programming Language]

So to your "deepest possible philosophical," unowned includes a precondition that does not exist in weak. This precondition exists outside the program, and must be proven by programmer, not the compiler, in order to ensure a well-formed program.

To whether there is a reason to use unowned, there certainly is if we're taking an absolutest stance (as in your question). It is the tightest type in cases where the precondition is known to be true. weak is a weaker type than unowned; it expresses fewer preconditions. Good type theory encourages us to use the strongest (most restrictive; fewest legal values) types we can, and unowned is a stronger type than weak.

In a non-absolutist ("practical") sense, the result of picking a stronger type is simpler code. When you use weak, you have to constantly re-assert the precondition that it is not nil every time you use it and handle the cases where it is (possibly inserting fatalError which just reinvents unowned with more work). Using unowned lets you assert this precondition one time. This creates simpler, more correct code. I've never used unowned for speed. I've always used it to avoid answering over and over again "but what if it's nil?" in code where it must never be nil.

weak vs unowned in Swift. What are the internal differences?

My question is, what is the point in having two such similar concepts? What are the internal differences that necessitate having two keywords for what seem essentially 99% the same thing?

They are not at all similar. They are as different as they can be.

  • weak is a highly complex concept, introduced when ARC was introduced. It performs the near-miraculous task of allowing you to prevent a retain a cycle (by avoiding a strong reference) without risking a crash from a dangling pointer when the referenced object goes out of existence — something that used to happen all the time before ARC was introduced.

  • unowned, on the other hand, is non-ARC weak (to be specific, it is the same as non-ARC assign). It is what we used to have to risk, it is what caused so many crashes, before ARC was introduced. It is highly dangerous, because you can get a dangling pointer and a crash if the referenced object goes out of existence.

The reason for the difference is that weak, in order to perform its miracle, involves a lot of extra overhead for the runtime, inserted behind the scenes by the compiler. weak references are memory-managed for you. In particular, the runtime must maintain a scratchpad of all references marked in this way, keeping track of them so that if an object weakly referenced goes out of existence, the runtime can locate that reference and replace it by nil to prevent a dangling pointer.

In Swift, as a consequence, a weak reference is always to an Optional (exactly so that it can be replaced by nil). This is an additional source of overhead, because working with an Optional entails extra work, as it must always be unwrapped in order to get anything done with it.

For this reason, unowned is always to be preferred wherever it is applicable. But never use it unless it is absolutely safe to do so! With unowned, you are throwing away automatic memory management and safety. You are deliberately reverting to the bad old days before ARC.

In my usage, the common case arises in situations where a closure needs a capture list involving self in order to avoid a retain cycle. In such a situation, it is almost always possible to say [unowned self] in the capture list. When we do:

  • It is more convenient for the programmer because there is nothing to unwrap. [weak self] would be an Optional in need of unwrapping in order to use it.

  • It is more efficient, partly for the same reason (unwrapping always adds an extra level of indirection) and partly because it is one fewer weak reference for the runtime's scratchpad list to keep track of.

unowned vs. weak. Why we should prefer unowned?

Weak references are automatically set to nil once the object they point to gets deallocated. For this to be possible in Swift, those must be declared as var and optional:

class SomeOtherClass {
weak var weakProperty: SomeClass?
}

This is fine if the weakProperty can become nil while the instance of SomeOtherClass is still alive and we want to check for that before using it (delegates are one such example). But what if some reference should never logically be nil and we still want to prevent a retain cycle? In Objective-C any object reference can be nil (and messaging nil always fails silently) so there is no dilemma, we always use weak. But Swift doesn't have nilable references at all. We use optionals for something that can semantically lack value. But we shouldn't be forced to use optionals for something that must always have value, just to be able to break a retain cycle. Such practice would go against the intended semantics of optionals.

That's where unowned comes in. It comes in two flavours - unowned(safe) and unowned(unsafe). The latter is dangerous and it's equivalent to assign and unsafe_unretained from Objective-C. But the former, which is the default one (at least while debugging; not sure if they optimise it to unowned(unsafe) in release builds), will reliably crash your app if the referenced object gets prematurely deallocated. Sure, your app will crash if something goes wrong, but that's much easier to debug than failing silently. It should only fail silently when you actually want that (in which case you would use weak)

Difference Between weak & unowned in respect to ARC memory management in Swift 3.1

The most important difference is that unowned variables are very dangerous in Swift.

weak is an optional type, unowned is NOT.

This means that you can create code that uses weak as part of the logic. (think of asynchronous actions that take place only if a view controller is still being shown on the screen, when the code is ran, if the reference is "weak" it will fail silently without causing any other issues if the code is written correctly)

On the other hand, when a variable is unowned you are basically saying that this variable will always refer to something. And unlike weak, if you call it and there's nothing it will crash.

You generally never wanna use unowned. (I haven't come across any case where I had to). On the other hand, "weak self" variables are quite common when writing blocks.

You can see a good explanation on this question:

Shall we always use [unowned self] inside closure in Swift

EDIT: Actually, check the first and second most voted answers. They provide a clear explanation on WHEN to use unowned and how it works. The second even has pictures!

What is the difference between a weak reference and an unowned reference?

Both weak and unowned references do not create a strong hold on the referred object (a.k.a. they don't increase the retain count in order to prevent ARC from deallocating the referred object).

But why two keywords? This distinction has to do with the fact that Optional types are built-in the Swift language. Long story short about them: optional types offer memory safety (this works beautifully with Swift's constructor rules - which are strict in order to provide this benefit).

A weak reference allows the possibility of it to become nil (this happens automatically when the referenced object is deallocated), therefore the type of your property must be optional - so you, as a programmer, are obligated to check it before you use it (basically the compiler forces you, as much as it can, to write safe code).

An unowned reference presumes that it will never become nil during its lifetime. An unowned reference must be set during initialization - this means that the reference will be defined as a non-optional type that can be used safely without checks. If somehow the object being referred to is deallocated, then the app will crash when the unowned reference is used.

From the Apple docs:

Use a weak reference whenever it is valid for that reference to become
nil at some point during its lifetime. Conversely, use an unowned
reference when you know that the reference will never be nil once it
has been set during initialization.

In the docs, there are some examples that discuss retain cycles and how to break them. All these examples are extracted from the docs.

Example of the weak keyword:

class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
}

class Apartment {
let number: Int
init(number: Int) { self.number = number }
weak var tenant: Person?
}

And now, for some ASCII art (you should go see the docs - they have pretty diagrams):

Person ===(strong)==> Apartment
Person <==(weak)===== Apartment

The Person and Apartment example shows a situation where two properties, both of which are allowed to be nil, have the potential to cause a strong reference cycle. This scenario is best resolved with a weak reference. Both entities can exist without having a strict dependency upon the other.

Example of the unowned keyword:

class Customer {
let name: String
var card: CreditCard?
init(name: String) { self.name = name }
}

class CreditCard {
let number: UInt64
unowned let customer: Customer
init(number: UInt64, customer: Customer) { self.number = number; self.customer = customer }
}

In this example, a Customer may or may not have a CreditCard, but a CreditCard will always be associated with a Customer. To represent this, the Customer class has an optional card property, but the CreditCard class has a non-optional (and unowned) customer property.

Customer ===(strong)==> CreditCard
Customer <==(unowned)== CreditCard

The Customer and CreditCard example shows a situation where one property that is allowed to be nil and another property that cannot be nil has the potential to cause a strong reference cycle. This scenario is best resolved with an unowned reference.

Note from Apple:

Weak references must be declared as variables, to indicate that their
value can change at runtime. A weak reference cannot be declared as a
constant.

There is also a third scenario when both properties should always have a value, and neither property should ever be nil once initialization is complete.

And there are also the classic retain cycle scenarios to avoid when working with closures.

For this, I encourage you to visit the Apple docs, or read the book.

Why would I ever use unowned self?

unowned has a marginal performance advantage over weak because the runtime doesn't have to keep track of the reference to turn it into nil when the object goes away.

In respect of retain cycles (well, strong reference cycles), neither weak nor unowned creates a strong reference (in pre ARC terms, neither increments the retain count) so there is no danger of a reference cycle, in fact, that is why you need to specify weak or unowned for self in closures.

Also, with unowned you can use the reference as a non optional, so you don't have to put any code in the closure to unwrap it.

I always use weak unless there is a really good performance reason not to.

NB in your code, I do not think either is necessary because the closure is not escaping i.e. The reference to it taken in the function call foo does not persist after the end of foo's scope.

What is the difference in Swift between 'unowned(safe)' and 'unowned(unsafe)'?

From what I understand, although I can't find a definitive source from Apple, unowned can be broken into two flavors, safe and unsafe.

A bare unowned is unowned(safe): it is a specially wrapped reference which will throw an exception when a dealloced instance is referenced.

The special case is unowned(unsafe): it is the Swift equivalent of Objective C's @property (assign) or __unsafe_unretained. It should not be used in a Swift program, because its purpose is to bridge to code written in Objective C.

So, you will see unowned(unsafe) when looking at the import wrapper for Cocoa classes, but don't use it unless you have to, and you will know when you have to.


Update

__unsafe_unretained is a simple pointer. It will not know when the instance being pointed at has be dealloced, so when it's dereferenced, the underlying memory could be garbage.

If you have a defect where a dealloced __unsafe_unretained variable is being used, you will see erratic behavior. Sometimes enough of that memory location is good enough so the code will run, sometimes it will have been partially overwritten so you will get very odd crashes, and sometimes that memory location will contain a new object so you will get unrecognized selector exceptions.

Transitioning to ARC Release Notes

__unsafe_unretained specifies a reference that does not keep the referenced object alive and is not set to nil when there are no strong references to the object. If the object it references is deallocated, the pointer is left dangling.



Related Topics



Leave a reply



Submit