Swift Substring

在swift中,当我们使用split方法的时候会返回一个Substring数组:
public func split(maxSplits: Int = default, omittingEmptySubsequences: Bool = default, whereSeparator isSeparator: (Character) throws -> Bool) rethrows -> [Substring]

这跟java或者ObjectC不同,在其他语言中我们将会得到一个String数组,为何swift返回一个新的类型Substring呢?

解释这个问题之前,先来看另外一个问题:
如何提升split方法的效率?

split方法就是根据特定字符串将原数组切分成不同的部分,我们知道String的存储比较特殊,一般都是在堆上,如果切分之后的子串也都存在堆上,无疑是一个巨大的开销,况且方法调用者并不一定要用到每一个子串。

怎么办呢?

那就共享内存

Substring
When you create a slice of a string, a Substring instance is the result. Operating on substrings is fast and efficient because a substring shares its storage with the original string. The Substring type presents the same interface as String, so you can avoid or defer any copying of the string’s contents.

split方法返回的每一个字符串子串不额外开辟内存空间,而是使用原数组的地址,这样就可以省下分配空间的开销。这是内部实现,无论是使用Substring还是String都可以做到,那么回到最初的问题,Substring有啥优势?

答案就是,这是一种优秀的编程思想!

考虑下面的case:

let bigContent : String = xxxx//获取一大段文字
let partOfIt = splitContent(bigContent)//截取一小部分
summaryLabel.text = partOfIt//设置UILabel

根据上面的分析我们知道Substring和原字符串是共享内存的,因此当上述逻辑执行完毕之后,只要summaryLabel没有销毁,bigContent所指向的字符串就不会释放,即使我们只使用了该字符串的一部分。

为避免上述内存泄漏情况的出现,我们应当给summaryLabel分配一个新的String

summaryLabel.text = String(partOfIt)

这样bigContent该释放就释放,和summaryLabel不再相关。

那为什么要用Substring?因为如果split返回的是[String],粗心的程序员很难会考虑到这么深入的问题,内存泄漏很容易发生。因此在API设计的时候,设置一个新的TypeSubstring,如果写的是summaryLabel.text = partOfIt编译器会报错,提示类型转化。

Important
Don’t store substrings longer than you need them to perform a specific operation. A substring holds a reference to the entire storage of the string it comes from, not just to the portion it presents, even when there is no other reference to the original string. Storing substrings may, therefore, prolong the lifetime of string data that is no longer otherwise accessible, which can appear to be memory leakage.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,364评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,273评论 19 139
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 33,742评论 18 399
  • 首页 资讯 文章 资源 小组 相亲 登录 注册 首页 最新文章 IT 职场 前端 后端 移动端 数据库 运维 其他...
    Helen_Cat阅读 9,467评论 1 10
  • 1.秦至晚清都不是封建制 封建,把土地册封给诸侯,让这些被册封的人去建立国家。而秦之后的王朝实行的都是中央集权制。...
    独孤无尘阅读 4,809评论 0 0

友情链接更多精彩内容