Group Group Group Group Group Group Group Group Group

Need help understanding the use of defer in the LinkedList pop() method

#1

What is defer accomplishing in the pop method?

@discardableResult
public mutating func pop() -> Value? {
  defer {
    head = head?.next
    if isEmpty {
        tail = nil 
    }
  }
  return head?.value
}

Thanks for the insight!

#2

Let’s see. Here’s what I’ve come up with if you don’t use defer:

let returnVal = head?.value

head = head?.next
if isEmpty {
  tail = nil
}

return returnVal

In this case, using defer allows you to avoid instantiating a new variable.

#3

Is this an aesthetic optimization, as in coding style, or is this a performance optimization? Seems the same work needs to be done to save the value explicitly with the instantiation or implicitly with the defer.

#4

There should be a performance impact, but I’m not sure which way it’ll go. On one hand, using defer avoids introducing a new variable. On the other hand, the compiler will need to transform defer to a different set of instructions. Depending what that is, it could introduce some overhead.

I’m not sure which way is more performant!

Our tech editor made this change, and IMO it is mostly aesthetic. It is nice that we don’t have to worry about extra variables though.