是什么原因,Swift 应该比 Objective-C 快得多? [英] Whats the cause, Swift is supposed to be that much faster than Objective-C?

查看:55
本文介绍了是什么原因,Swift 应该比 Objective-C 快得多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如 Craig 在 Swift 的公告中透露的那样,据说到目前为止它比 Objective-C 更快.

As Craig revealed within the announcement of Swift, it is said to be faster than Objective-C by far.

但我不太相信这种比较,因为正确实现的算法在 C 中应该是最快的,因为它可以被编译器高度优化并且本质上是硬件友好的.所以我猜 Swift 能得到的最好的性能,应该是 C 中相同算法的性能.

But i'm not that convinced by that comparison because a properly implemented algorithm should be fastest in C, because it can be highly optimized by the compiler and is hardware-friendly by nature. So I would guess the best performance Swift could get, would be the performance of the same algorithm in C.

既然 C 是 Objective-C 的一部分,为什么 Objective-C 和 Swift 的性能之间会有这么大的差距?

And as C is part of Objective-C, why is there a that big gap between Objective-C and Swift performance?

我能想象到的唯一原因是 Apple 使用 NSNumbers 等而不是 C 类型,但不应该作为 Obj-C - Swift 比较的基础,对吧?

The only reason I could imagine is Apple using NSNumbers and such instead of C types, but should not be the base for a Obj-C - Swift comparison, right?

推荐答案

这主要是推测(虽然是知情推测),但我的两大理论是:

This is largely speculation (although informed speculation) but my two big theories are:

1) No 减少动态方法调度.Objective-C 中的每个方法调用都经过 objc_msgSend.在最快的情况下,这可以像 16 条指令一样快,但也可能慢很多.Swift 在比 Objective-C 更少的情况下会产生这种惩罚,例如:对 swift-only 协议方法的方法调用不会命中 objc_msgSend,但是如果协议是在 Obj-C 中声明的,或者如果swift 协议用 @objc 修饰(这样它也可以被 Objective-C 对象采用),然后对 swift 对象采用的该协议中的方法的方法调用似乎是通过 objc_msgSend.

1) No Reduced dynamic method dispatch. Every method call in Objective-C goes through objc_msgSend. In the fastest case, this can be as quick as 16 instructions, but it can also be a lot slower. Swift will incur this penalty in fewer situations than Objective-C will, for instance: method calls to swift-only protocol methods do not hit objc_msgSend, but if the protocol is declared in Obj-C, or if the swift protocol is decorated with @objc (such that it can be adopted by Objective-C objects as well), then method calls to methods in that protocol adopted by swift objects appear to be dispatched via objc_msgSend.

2) 避免堆分配.在 Objective-C 中,(实际上)每个对象都是堆分配的.使用静态类型系统,编译器可以推断出更多关于对象生命周期的信息,并在堆栈上分配它,除非它必须跨越 Objective-C 边界(或者太大而无法在堆栈上分配).

2) Avoiding heap allocations. In Objective-C, (effectively) every object is heap allocated. With a static type system, the compiler can infer more about the lifecycle of an object and allocate it on the stack unless it has to cross the Objective-C boundary (or is too big to be allocated on the stack).

我怀疑 #2 是这两者中更大的一个,但两者都可能是重要的贡献者.我敢肯定这不仅仅是这个,但这两个很有可能的贡献者.

I suspect that #2 is the much bigger of these two, but both are likely significant contributors. I'm sure there's more to it than just this, but these are two very likely contributors.

这篇关于是什么原因,Swift 应该比 Objective-C 快得多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆