博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Swift Array 元素个数判断为0的方法哪种更好
阅读量:7079 次
发布时间:2019-06-28

本文共 1952 字,大约阅读时间需要 6 分钟。

在日常开发中,经常会遇到判断一个Array中元素个数是否为0。一般来说,有两种方法,一种是isEmpty,一种是array.count == 0。那哪一种方法更好呢?在苹果的官方文档中,isEmpty方法上有这样一段注释

/// 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)复制代码

大致意思就是,当判断你的集合是否为空时,推荐使用isEmpty属性来代替判断count属性是否等于0。因为集合类型的count属性会遍历集合里的所有元素。isEmpty属性的时间复杂度为O(1)。 接下来我们就从源代码角度来分析一下这2者的区别吧。以下的代码位于githubstdlib/public/core/Collection.swift文件里。

public protocol Collection: Sequence {	var isEmpty: Bool { get }	var count: Int { get }		var startIndex: Index { get }	var endIndex: Index { get }}复制代码

首先,isEmptycount都是Collection协议的计算型属性。其次,都有一个默认实现。

isEmpty 实现

extension Collection {	public var isEmpty: Bool {   		return startIndex == endIndex  	}}复制代码

isEmpty方法的实现很简单,判断startIndexendIndex是否相等就可以了。那startIndexendIndex又是2个计算型属性,那么这2个的实现又是怎么样的呢?在这个文件里我们没有找到默认实现,所以我们就前往同层文件夹的Array.swift文件里去查看一下了。 startIndex的实现很简单,直接返回了一个0

public var startIndex: Int {    return 0  }复制代码

endIndex的相对就稍微复杂一点了

@inlinablepublic var endIndex: Int {	@inlinable    get {      	return _getCount()    } }  internal func _getCount() -> Int {	return _buffer.count}复制代码

看到这儿,里面的再看下去就太深了(我也看不明白了),姑且当作_bufferArray类型的内部实现吧。

count 实现

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方法内部调用了一个distance(from:to:)的方法,而且在distance内部有一个while循环遍历直到start==end,那么count的事件复杂度就是o(n)

因此2个属性相比,在使用的时候,最好还是使用isEmpty属性判断Array元素是否为空。

转载于:https://juejin.im/post/5cf542015188253a2b01cb07

你可能感兴趣的文章
linux开机自启动(开机启动)的三种方法
查看>>
ORACLE表分区
查看>>
hdoj2602_Bone Collector
查看>>
【转】如何解决系统事件出现DCOM 10009错误?
查看>>
C++_CFileFind文件查找
查看>>
VS_生成事件
查看>>
nginx+django1.6.8+uwsgi+virtualenv +virtualenvwrapper 多站点
查看>>
双击打不开office文件
查看>>
中国最早的CCIE__孙晖
查看>>
《Objective-C 程序设计(第4版)》书评!
查看>>
Xcode真机调试identifier not avaliable错误
查看>>
Dockerfile制作LAMP
查看>>
sublime text3安装及配置
查看>>
gitignore配置
查看>>
dell远程控制卡iDRAC如何重启?
查看>>
Mybatis-Plus 真好用(乡村爱情加持)
查看>>
信用卡相关
查看>>
Koa (koajs) 基于 Node.js 平台的下一代 web 开发框架
查看>>
ext表格grid----重写applySort方法,使支持按中文首字母排序
查看>>
使用git命令提取两次提交之间的差异文件
查看>>