As Craig revealed within the announcement of Swift, it is said to be faster than Objective-C by far.
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.
And as C is part of Objective-C, why is there a that big gap between Objective-C and Swift performance?
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 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) 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).
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.