Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

用 struct 还是 class?让 Swift-NIO 的开发者来告诉你 #1915

Closed
kemchenj opened this issue Jan 15, 2020 · 1 comment
Closed

用 struct 还是 class?让 Swift-NIO 的开发者来告诉你 #1915

kemchenj opened this issue Jan 15, 2020 · 1 comment
Assignees
Labels
Swift Swift 使用及优化 性能优化 iOS 性能优化相关 视频

Comments

@kemchenj
Copy link
Contributor

kemchenj commented Jan 15, 2020

推荐收录

链接

High performance systems in Swift - Johannes Weiss

理由

演讲者分享了他在 Swift-NIO 开发时的一些经验,在选择 class 和 struct 时,Swift 社区有一个普遍的共识是 struct 绝大部分情况下比 class 好,能用 struct 就用 struct。

但实际在 Swift-NIO 的 benchmark 里这件事情并不成立,将 HTTPRequestHeader 这个 struct 直接改成 class 之后,性能竟然比之前提升了 4 倍,并且内存占用也变得更低,他在演讲里很详细的分析了两种方式在运行时的内存分配过程,大家有兴趣的话可以去看。

所以这就是结论?class 性能比 struct 好?这件事情还没有结束,用 class 意味着 HTTPRequestHeader 这个类型失去了值语义,写 Swift 的人都能懂这是多么重要的一个保证,这意味着你对于一个实例的独占,你对于这个实例的任何 Mutation 都不会导致其它地方发生问题。

想要保持值语义的同时使用 class?使用 Copy-On-Write(COW) 就可以达到这个目的,Swift-NIO 最终也是这么做的,但这并不意味着 COW 就是最好的,只有在特定的使用场景下,class 才会比 struct 性能更好,所以 Swift-NIO 里只有三个类型使用了 COW 进行实现。

最后他提到 struct 和 class 的选择其实跟性能无关,只跟我们想要表达的语义有关,如果遇上了 class 比 struct 更好的场景,那再用 COW 把这些性能相关的细节封装在内部即可,保持 API 兼容的同时还能得到更好的性能。

PS:SwiftFormat 的作者 Nick 最近也在 Twitter 上分享了类似的优化经验以及相关的原理分析,也是推荐一读。

@kemchenj kemchenj added 视频 Swift Swift 使用及优化 性能优化 iOS 性能优化相关 labels Jan 15, 2020
@Adrift001
Copy link

不习惯用struct, class可以到处引用, 到处修改. struct就不行. 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Swift Swift 使用及优化 性能优化 iOS 性能优化相关 视频
Projects
None yet
Development

No branches or pull requests

3 participants