How is Swift faster than objective C
The official Apple website claims that Swift is 2.6 faster than Objective-C. Swift and Objective-C are both statically typed languages that use the same iOS SDK and LLVM(Low Level Virtual Machine)compiler.Still swift is faster due to the following reasons.
- Support of Dynamic libraries.
Dynamic libraries supported by Swift.They are loaded directly into an app’s memory and will optimize the app’s performance. Direct connection with the app allows them to be updated independently from the OS. It helps keep your solution current, reduces the app size, and speeds up the load time of new content.
Objective-C doesn’t support dynamic libraries and this is a major disadvantage. The thing is that they are larger in size because external programs are built in the executable files. Dynamic libraries are smaller because only one copy of dynamic library is being stored in memory.
2. Runtime code compilation
Objective C uses runtime code compilation, rather than the compile time. This means that when the Objective-C object calls for another object in the code, there is an extra level of indirection involved. Generally, this happens very fast but when the code compilation happens a significant number of times, it becomes measurable,whereas swift takes lesser time for compilation .
3. Reference types Vs Value types
Swift’s String,Dictionary, and Array are structs. That means they’re value-typed and don’t support inheritance, so Swift can statically link and can inline calls to their methods. They’re also copy-on-write, so if you’re only reading data from one of these data structures, Swift can turn a lot of accesses into pointer arithmetic with bounds checks.
4. Usage of constants & Optionals
- Swift allows and encourages the use of constants much more than C ever did. The optimizer can assume that constants never change — even backdoor techniques like forming an UnsafePointer to the constant are banned — and so it can safely cache previously-fetched values and perform other optimizations.
- Optionals ensure that certain pointers can never be nil, so the compiler can omit nil checks.
6.Some more points to note
- Swift objects can call one another without needing to perform the message sending which was a bottleneck on Objective-C performance.
- Objective-C’s objects come with magical properties which allows introspection and dynamic handling of messages. This is super powerful, but adds a cost to every single message.
- Swift objects don’t require this. So can be much more lightweight. In theory there’s no reason why Swift code could not be as fast as C++.
- In simple tests, with the optimiser set to “11”, Swift code seems to have a similar performance to C / C++.