Increasing Performance by Reducing Dynamic Dispatch
https://developer.apple.com/swift/blog/?id=39
Increasing Performance by Reducing Dynamic Dispatch
Like many other languages, Swift allows a class to override methods and properties declared in its superclasses. This means that the program has to determine at runtime which method or property is being referred to and then perform an indirect call or indirect access. This technique, called dynamic dispatch, increases language expressivity at the cost of a constant amount of runtime overhead for each indirect usage. In performance sensitive code such overhead is often undesirable. This blog post showcases three ways to improve performance by eliminating such dynamism: final, private, and Whole Module Optimization.
Consider the following example:
class ParticleModel {
var point = ( 0.0, 0.0 )
var velocity = 100.0
func updatePoint(newPoint: (Double, Double), newVelocity: Double) {
point = newPoint
velocity = newVelocity
}
func update(newP: (Double, Double), newV: Double) {
updatePoint(newP, newVelocity: newV)
}
}
var p = ParticleModel()
for i in stride(from: 0.0, through: 360, by: 1.0) {
p.update((i * sin(i), i), newV:i*1000)
}
As written, the compiler will emit a dynamically dispatched call to:
- Call update on p.
- Call updatePoint on p.
- Get the property point tuple of p.
- Get the property velocity of p.
This might not be what you would expect when looking at this code. The dynamic calls are necessary because a subclass of ParticleModel might override point or velocity with a computed property or override updatePoint() or update() with new implementations.
In Swift, dynamic dispatch calls are implemented by looking up a function from a method table and then performing an indirect call. This is slower than performing a direct call. Additionally, indirect calls also prevent many compiler optimizations, making the indirect call even more expensive. In performance critical code there are techniques you can use to restrict this dynamic behavior when it isn’t needed to improve performance.
Use final when you know that a declaration does not need to be overridden.
The final keyword is a restriction on a class, method, or property that indicates that the declaration cannot be overridden. This allows the compiler to safely elide dynamic dispatch indirection. For instance, in the following point and velocity will be accessed directly through a load from the object’s stored property and updatePoint() will be called via a direct function call. On the other hand, update() will still be called via dynamic dispatch, allowing for subclasses to override update() with customized functionality.
class ParticleModel {
final var point = ( x: 0.0, y: 0.0 )
final var velocity = 100.0
final func updatePoint(newPoint: (Double, Double), newVelocity: Double) {
point = newPoint
velocity = newVelocity
}
func update(newP: (Double, Double), newV: Double) {
updatePoint(newP, newVelocity: newV)
}
}
It is possible to mark an entire class as final by attaching the attribute to the class itself. This forbids subclassing the class, implying that all functions and properties of the class are final as well.
final class ParticleModel {
var point = ( x: 0.0, y: 0.0 )
var velocity = 100.0
// ...
}
Infer final on declarations referenced in one file by applying the private keyword.
Applying the private keyword to a declaration restricts the visibility of the declaration to the current file. This allows the compiler to find all potentially overriding declarations. The absence of any such overriding declarations enables the compiler to infer the final keyword automatically and remove indirect calls for methods and property accesses.
Assuming there is no class overriding ParticleModel in the current file, the compiler can replace all dynamically dispatched calls to private declarations with direct calls.
class ParticleModel {
private var point = ( x: 0.0, y: 0.0 )
private var velocity = 100.0
private func updatePoint(newPoint: (Double, Double), newVelocity: Double) {
point = newPoint
velocity = newVelocity
}
func update(newP: (Double, Double), newV: Double) {
updatePoint(newP, newVelocity: newV)
}
}
As in the previous example, point and velocity are accessed directly and updatePoint() is called directly. Again, update() will be invoked indirectly due to update() not being private.
Just like with final, it is possible to apply the private attribute to the class declaration itself causing the class to be private and thus all of the properties and methods of the class as well.
private class ParticleModel {
var point = ( x: 0.0, y: 0.0 )
var velocity = 100.0
// ...
}
Use Whole Module Optimization to infer final on internal declarations.
Declarations with internal access (the default if nothing is declared) are only visible within the module where they are declared. Because Swift normally compiles the files that make up a module separately, the compiler cannot ascertain whether or not an internal declaration is overridden in a different file. However, if Whole Module Optimization is enabled, all of the module is compiled together at the same time. This allows the compiler to make inferences about the entire module together and infer final on declarations with internal if there are no visible overrides.
Let’s go back to the original code snippet, this time adding some extra public keywords to ParticleModel.
public class ParticleModel {
var point = ( x: 0.0, y: 0.0 )
var velocity = 100.0
func updatePoint(newPoint: (Double, Double), newVelocity: Double) {
point = newPoint
velocity = newVelocity
}
public func update(newP: (Double, Double), newV: Double) {
updatePoint(newP, newVelocity: newV)
}
}
var p = ParticleModel()
for i in stride(from: 0.0, through: times, by: 1.0) {
p.update((i * sin(i), i), newV:i*1000)
}
When compiling this snippet with Whole Module Optimization the compiler can infer final on the properties point, velocity, and the method call updatePoint(). In contrast, it can not be inferred that update() is final since update() has public access.
Increasing Performance by Reducing Dynamic Dispatch的更多相关文章
- Dynamic dispatch
Dynamic dispatch动态调度.动态分发 In computer science, dynamic dispatch is the process of selecting which im ...
- Dynamic dispatch mechanisms
Normally, in a typed language, the dispatch mechanism will be performed based on the type of the arg ...
- this inspection detects names that should resolved but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases. Top-level and class-level items are sup
输入第一行代码:import logging;logging.basicConfig(level==logging.INFO) 提示:this inspection detects names tha ...
- 【PyCharm编辑器】之无法导入引用手动新建的包或类,报:This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck typing, this is possible in a limited but useful number of cases.
一.现象描述 如下图所示,手动新建个类包calculator.py,想在test.py文件引用它,发现一直报红线,引用失败 Unresolved reference 'calculator' less ...
- swift -Dynamic Dispatch
These instructions perform dynamic lookup of class and generic methods. The class_method and super_m ...
- Only Link: What's the difference between dynamic dispatch and dynamic binding
http://stackoverflow.com/questions/20187587/what-is-the-difference-between-dynamic-dispatch-and-late ...
- 【Python】This inspection detects names that should resolve but don't. Due to dynamic dispatch and duck
情况一:导包import时发生错误,请参考这两位 https://blog.csdn.net/zhangyu4863/article/details/80212068https://www.cnblo ...
- [Angular] Increasing Performance by using Pipe
For example you make a function to get rating; getRating(score: number): string { let rating: string ...
- 唐巧的iOS技术博客选摘
1. 那些被遗漏的objective-c保留字:http://blog.devtang.com/blog/2013/04/29/the-missing-objc-keywords/ 2. 使用cr ...
随机推荐
- 使用springboot mybatis 查询时实体类中的驼峰字段值为null
看到返回结果以后主要分析了一下情况: 实体类的get.set方法确实 mapper.xml文件中的resultMap.resultType等原因导致 数据库中数据存在问题 经过检查与验证发现以上都不存 ...
- C 编程环境搭建 Window 篇
前言 - 简介 我们在写代码的过程中, 不可避免的重度依赖所处的开发环境. 本文重点带大家在 Window 搭建 C 简单控制台项目. 当作存档, 用于记录项目搭建各种重复操作. 在详细过程之前, ...
- The Xor-longest Path(trie树)
题目: #10056. 「一本通 2.3 练习 5」The XOR-longest Path 解析: 做完#10051后就不是很难了 继续利用异或的性质有\(dis(u,v) = dis(1,u)\o ...
- Java自学-类和对象 属性初始化
如何进行Java的属性初始化 步骤 1 : 对象属性初始化 对象属性初始化有3种 声明该属性的时候初始化 构造方法中初始化 初始化块 . public class Hero { public Stri ...
- 【转载】C#的DataTable使用NewRow方法创建新表格行
在C#的DataTable数据表格操作过程中,DataRow类表示DataTable中的数据行信息,但DataRow没有可以直接实例化的构造方法,在创建DataTable的新行的时候,不可直接使用Da ...
- js实现数组去重(方式大汇总)
方法一:循环判断当前元素与其后面所有元素对比是否相等,如果相等删除:(执行速度慢) var arr = [1,23,1,1,1,3,23,5,6,7,9,9,8,5]; function remove ...
- 1. vue.js介绍
1. 什么是vue.js Vue.js 是目前最火的一个前端框架,React是最流行的一个前端框架(React除了开发网站,还可以开发手机App, Vue语法也是可以用于进行手机App开发的,需要借助 ...
- xenserver 备份和还原
1. 备份和还原xenserver host系统 //备份 # xe host-backup file-name=[name.xbk] -s [ip] -u [username] -pw [passw ...
- Unity手游汉化笔记②:使用UABE替换TTF字体
总的笔记:https://www.cnblogs.com/guobaoxu/p/12055930.html 目录 一.分析 二.思路 三.具体实践 四.总结 Unity版本:2018.4.5f1 工具 ...
- io详解
1.io类