In the daily development, often encounter to determine a Array
number of elements is zero. Generally, there are two methods, one is isEmpty
, one is array.count == 0
. That Which method is better? Apple's official documentation, isEmpty
such a comment on the method
/// When you need to check whether your collection is empty, use the `isEmpty` property instead of checking that the `count` property equal to zero.
/// For collections that dont conform `RandomAccessCollection`, accessing the `count` property iterates through the elements of the collection.
- Complexity: O(1)
复制代码
Generally it means that when you determined whether the set is empty, it is preferably isEmpty
property instead determines count
attribute is equal to zero. Because the collection type of count
property will traverse the collection of all the elements. isEmpty
Attribute is time complexity O (1). Next we went from the perspective of the source code to analyze the difference between these two persons it. The following code is in github
the stdlib/public/core/Collection.swift
file.
public protocol Collection: Sequence {
var isEmpty: Bool { get }
var count: Int { get }
var startIndex: Index { get }
var endIndex: Index { get }
}
复制代码
First of all, isEmpty
and count
are Collection
computational property agreement. Secondly, there is a default implementation.
isEmpty achieve
extension Collection {
public var isEmpty: Bool {
return startIndex == endIndex
}
}
复制代码
isEmpty
Implementation is simple, judge startIndex
and endIndex
equality on it. That startIndex
and endIndex
again two computational properties, then this two implementations is kind of how it? In this document we did not find the default implementation, so we went with the layer folder Array.swift
files go look up. startIndex
Implementation is very simple, straightforward returns a0
public var startIndex: Int {
return 0
}
复制代码
endIndex
Relative to the slightly more complex
@inlinable
public var endIndex: Int {
@inlinable
get {
return _getCount()
}
}
internal func _getCount() -> Int {
return _buffer.count
}
复制代码
See here, look down on the inside too deep (I also do not understand), tentatively as _buffer
is Array
the internal type to achieve it.
count to achieve
public var count: Int {
return distance(from: startIndex, to: endIndex)
}
public func distance(from start: Index, to end: Index) -> Int {
_precondition(start <= end,
"Only BidirectionalCollections can have end come before start")
var start = start
var count = 0
while start != end {
count = count + 1
formIndex(after: &start)
}
return count
}
复制代码
count
Internal method calls a distance(from:to:)
method, and in distance
the interior there is a while
loop through until start==end
then count
the complexity of the event is o(n)
.
Thus two properties compared to when in use, it is best to use isEmpty
attribute determines Array
whether the element is empty.
Reproduced in: https: //juejin.im/post/5cf542015188253a2b01cb07