Swift Basics 19 Swift lazy loading (lazy modifier)

Source: Internet
Author: User
Tags modifier prepare
Delayed loading or delayed initialization is a very common optimization method, when building and generating new objects, memory allocation will take time to run, and if there are some objects with complex properties and contents, this time is not negligible.

In addition, in some cases we do not immediately use all of the properties of an object, and by default the storage properties that are not used in a particular environment are initialized and assigned, as well as a waste. It is common to delay loading in other languages, including objective-c. When we first access a property, we determine whether the store behind the property already exists, if it exists, it returns directly, if it does not exist, it is initialized and stored and then returned. This allows us to defer the initialization of this property, separating it from the initialization time of the object containing it, to achieve the purpose of improving performance. Take Objective-c for example (although there is no time-consuming operation and no performance impact due to the use of delayed loading, but as a simple example, the problem can be well illustrated)://ClassA.h @property (nonatomic, copy)

NSString *teststring;
        CLASSA.M-(NSString *) teststring {if (!_teststring) {_teststring = @ "Hello";
     NSLog (@ "Only on first access output");
} return _teststring; After initializing the ClassA object, _teststring is nil. The Getter method is called only when the TestString property is first accessed, and is evaluated if it has not yet been initialized. For the convenience of confirmation, we also printed a log when we assigned the value.

We access this property several times later, because _teststring already has a value, so it will be returned directly. In Swift we use the Lazy keyword before the variable attribute to simply specify the delay load. For example, the above code, which we rewrite in Swift, would be: class ClassA {lazy var str:string = {Let str = "Hello" Print ("only in the first Access output ") return str} ()} When we use lazy as the property modifier, onlyThe ability to declare a property is a variable. In addition, we need to explicitly specify the property type and use a statement that can be assigned to this property to run when the property is first accessed.

If we access the str attribute of this instance multiple times, we can see that there is only one output. To simplify, if we don't need to do any extra work, we can write the assignment statement directly to the lazy attribute: lazy var str:string = "Hello" compared to the implementation in Objective-c, now the lazy to use more convenient

。

Another less noticeable is that in Swift's standard library We also have a set of lazy methods, which are defined as: Func lazy<s:sequencetype> (s:s), lazysequence<s> Func lazy<s:collectiontype where s.index:randomaccessindextype> (s:s), LAZYRANDOMACCESSC ollection<s> func lazy<s:collectiontype where s.index:bidirectionalindextype> (s:s)-&G T  
                lazybidirectionalcollection<s> func lazy<s:collectiontype where s.index:forwardindextype> (s:s) -Lazyforwardcollection<s> These methods can be combined with a method such as map or filter that accepts closures and runs, allowing the entire behavior to become delayed. Doing this in some cases can also be helpful for performance.  For example, when using map directly: let data = 1...3 let result = data.map {(i:int)-Int in print ("Processing \ (i)") return I  
   * 2} print ("Ready to access result") for I in result { Print ("Operation result is \ (i)")} print ("Done") the output of this is://processing 1//processing 2//processing 3//preparing access result//operation result is 2//After operation result is 4//Operation Post-knot The result is 6//the operation is complete and if we do a lazy operation first, we will be able to get the deferred runtime version of the container: let data = 1...3 to results = data.lazy.map {(i:int)-I NT in print ("Processing \ (i)") return I * 2} print ("Prepare access result") for I in result {print ("After operation result is \ (i)")} print (" Operation completed ") at this time results://Prepare access results//IS processing 1//operation result is 2//processing 2//operation result is 4//processing 3//operation result is 6//operation completed
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.