Understanding `append(_:)` implementation of _FixedArray16

Hello.
My question pertains to _FixedArray16 in the stdlib and is really simple: Why increment the count first, only to subtract from it right after, in order to store newValue?

extension _FixedArray16 {
  internal mutating func append(_ newElement: T) {
    _internalInvariant(count < capacity)
    _count += 1
    self[count-1] = newElement
  }
}

While writing this down I realised that they are not the same count:

var _count: Int8

// ...

internal var count: Int {
  @inline(__always) get { return Int(truncatingIfNeeded: _count) }
  @inline(__always) set { _count = Int8(newValue) }
}

But still I can't understand why not do this instead:

self[count] = newElement
_count += 1

Is there a performance reason behind this choice assuming they don't lead to the same machine code? If there is, can someone explain it to me?

Thank you.

The type has an invariant that a valid subscript index is greater or equal to zero, and less than _count. Your formulation would break that invariant; I'm sure it was written this way simply to make it more resistant to possible mistakes.

The subscript is defined at line 56 of FixedArray.swift

3 Likes

Oh right, that makes sense. Thanks!

Terms of Service

Privacy Policy

Cookie Policy