Swift Performance Exploration and optimization analysis

Source: Internet
Author: User
Tags gcd

Swift Performance Exploration and optimization analysis

Apple is the name of an advanced, safe and efficient new generation of programming languages when it launches Swift. The first two points have been vividly demonstrated in Swift's grammatical and linguistic features: such as trailing closures, enumeration of associated values, optional values, and mandatory type safety are all obvious advantages of Swift. But for a bit more efficient, it's not that obvious. At the WWDC conference in 2014, Apple announced that Swift had a performance beyond objective-c, even in some cases comparable to and exceeding C. But after Swift's release, many developers found that Swift performance was not as good as it was advertised. Even today, with Swift's evolution of 1.5, it is easy to fall into the trap of language performance with a slight carelessness. This article will analyze some of the performance considerations and practices used by Swift for Ios/os X development, as well as the experience of using Swift for more than a year to develop, as well as some corresponding approaches.

Why Swift's performance deserves to be expected

Swift has most of the features required for an efficient language. There is no comparison between an interpreted language such as Ruby or Python, and the binding of the method is done during compilation, as compared to the predecessor's Objective-c,swift, so the method call is no longer a Smalltalk-like message. Instead, you get the method address directly and make the call. Although Objective-c caches and optimizes the process of running-time lookup methods, it is undeniable that Swift's invocation is faster and more efficient.

Also, unlike Objective-c, Swift is a strongly typed language, which means that Swift's runtime is consistent with the type of code during compilation, so that the compiler can get enough information to optimize when generating intermediate and machine code. Although all are compiled using the LLVM Toolchain, Swift's compilation process is one more link than objective-c-generating swift intermediate code (Swift Intermediate Language,sil). The SIL contains many conversions based on type assumptions, which provide a good basis for further optimization at lower levels, and the analysis of SIL is also an effective way for us to explore Swift performance.

Finally, Swift has a good strategy and structure for memory usage. Most of the types in the Swift standard library are structs, with a wide range of value types and are the most recent in the programming language. The non-variability of the original value type often leads to the use and modification of values, which means that new objects are created, but Swift avoids unnecessary copying of value types and only allocates memory when necessary. This allows Swift to enjoy the benefits of immutability and avoid unnecessary sharing, while maintaining excellent performance

Testing for performance

This entry title, "The Art of Computer Programming" and the author of TeX Gartner, once said in the paper:

Premature optimization is the source of all evil.

in COCOA development, there are several common ways to test performance. The simplest of these is to monitor the elapsed time of a program by outputting log directly. In Cocoa we can use  cacurrentmediatime   for precise time. This method will call the Mach bottom  mach_absolute_time () , its return is a  mach based absolute Time unit , we can understand how the method executes by acquiring two times each time before and after the method call, and then calculating their interval:

Let start = Cacurrentmediatime ()

// ...

Let end = Cacurrentmediatime ()

Print ("Measuring time: \ (End-start)")

For ease of use, we can also encapsulate this code in a method so that we can easily use it where we need to test performance in the project:

Func measure (f: ()) {

Let start = Cacurrentmediatime ()

F ()

Let end = Cacurrentmediatime ()

Print ("Measuring time: \ (End-start)")

}

Measure {

Dosomeheavywork ()

}

Optimization means, common misuse and countermeasures

Multithreading, algorithm and data structure optimization

After identifying the code that needs to be improved, one of the most fundamental ways to optimize it is to improve it at the programming level. In the mobile client, for code that affects the smoothness of the UI, we can put it on a background thread to run it. Grand Central Dispatch (GCD) either NSOperation allows us to easily switch between threads, rather than worrying about thread scheduling. A typical example of using GCD to put heavy work into a background thread and then go back to the main thread operation after completion is this:

Let queue = Dispatch_get_global_queue (qos_class_default, 0)

Dispatch_async (queue) {

Long-running code that runs on a background thread

Dispatch_async (Dispatch_get_main_queue ()) {

Return to main thread action UI after end

}

}

Putting work to another thread while avoiding the main thread blocking, it does not reduce the actual execution time of the code. Further, we can consider improving the algorithm and the data structures used to improve efficiency. Depending on the problems encountered in the actual project, we will have different solutions, in this article, we have difficulty in covering and in-depth analysis of the situation, so here we will only mention some common principles.

For repetitive work, the proper use of caching can greatly improve efficiency, which is a priority in optimization. Cocoa in developmentNSCacheis a class that is dedicated to managing the cache, reasonably used and configuredNSCacheFrees developers from managing cache storage and invalidation. AboutNSCacheFor a detailed usage, see Nshipster's article on this and Apple's documentation.

In the process of development, the use of data structure selection is also an important link. The Swift standard library provides some very basic data structures, such asArrayDictionaryAndSetsuch as These data structures are in conjunction with generics, and generally provide us with sufficient performance while ensuring data type security. The complexity of the container type method for these data is marked by Apple in a document or note in the standard library. If the types and methods provided by the standard library do not meet the performance requirements, or if there is no data structure that meets the business requirements, then it is optional to consider using your own implementation.

If there are many mathematical calculations in the project that lead to efficiency problems, considering parallel computing can greatly improve program performance. IOS and OS X have a framework specifically optimized for digital signal processing, such as math or graphical computing: accelerate.framework, using the relevant APIs, we can easily and quickly complete many classic digital or image processing problems. Because this framework provides only a set of C APIs, it is difficult to use it directly in Swift. If the calculations you're dealing with in your project are relatively straightforward, you can also use Surge, a Swift project based on the accelerate framework that allows us to get incredible performance gains from parallel computing in our code.

most compiler optimizations

The Swift compiler is smart enough to help us remove unwanted code during compilation, or to inline (inline) processing some methods. Compiler-optimized strength can be controlled by parameters at compile time, and the Xcode project has debug and Release two compile configurations by default, and LLVM code Generation and Swift code Generation are not turned on in debug mode optimization, which guarantees the speed of compilation. In Release mode, LLVM uses "fastest, smallest [-os]" by default, and Swift Compiler defaults to "Fast [-O]" as the level of optimization. We also have a few additional optimization levels to choose, the higher the optimization level, the compiler for the source of changes in the amplitude and the optimization of the power to optimize, and the more time spent during compilation. While it is not a problem in most cases, it is still necessary to be aware that some optimization levels are based on aggressive optimization strategies, while some checks are disabled. This can lead to a potential error in the case of a complex source code. If you are using a high level of optimization, test the logic of the program running under Release and Debug repeatedly to prevent compiler optimizations from causing problems.

It is worth mentioning that the Swift compiler has a very useful optimization level: "Fast, Whole Module optimization", also known as-o-whole-module-optimization. At this level of optimization, the Swift compiler will consider all the source code in the entire module at the same time, and mark those types and methods that are not inherited and overloaded as final, which will avoid dynamically distributed calls as much as possible, or even inline the method to speed up the operation. Turning on this extra optimization will greatly increase the compilation time, so you should only open this option when the app is going to be published.

While the compiler is now smart enough to optimize, many optimizations that should be implemented may fail in the face of very complex writing situations. So keeping the code neat, clean and simple can help the compiler optimize its work to get efficient machine code.

Swift is a very new language, and it is developing at a high speed. Because Swift is now used only for COCOA development, it is inextricably linked to the COCOA framework. Many times for these reasons, our assessment of Swift performance is unfair. The language itself is designed with high performance in mind, and with Swift's open source and further evolution, as well as a complete rewrite of the supporting framework, we believe we can get better performance and compiler support at the language level.

The best optimization is not optimization. In software development, to ensure that the writing of the correct and concise code, at the beginning of the project to pay attention to the potential performance defects, the scalability of the consideration into the software construction, according to the actual needs of optimization, not to fall into the optimization of the vicious circle, which often allows us to avoid additional optimization time, To make our work more enjoyable.

Future CTO


Follow my CTO's path from now on
.

Number: Wlaicto


Swift Performance Exploration and optimization analysis

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.