Compare iOS network components: afnetworking VS asihttprequest (reprint)

Source: Internet
Author: User
Tags ftp protocol

In developing iOS applications, how to efficiently exchange data with the server-side API is a common problem. General developers will choose a third-party network component as a service to improve development efficiency and stability. These components encapsulate complex network underlying operations into friendly classes and methods, and add exception handling.

So, what are the most common components for everyone? How are these components improving development efficiency and stability? Which component is right for you, afnetworking (AFN) or asihttprequest (ASI)? Almost every iOS Internet app developer will face this choice, and it's not that easy to pick a good one from the two most commonly used components.

Just from the time nodes submitted by the two control versions, AFN's first submission was January 1 in 2011, when the ASI was already a 1.8+ version, and when AFN released version 1.0, October 2012, the ASI had stopped updating early. So it seems that AFN is the successor to ASI, and there seems to be no problem with the difficult choice mentioned before, and that is not the case. This article will make a simple comparison between the two aspects of usage, function, performance and principle to see what difference there is between them and how to choose.

1. Comparison of usage

First, it can be seen from the recommended usage that the design concept is quite different.

Figure 1,afn Sample code, initiating the request (from: POSTS.M)

AFN The official recommended method is to define a httpclient for a series of related requests, sharing a baseurl. Each request to the URL in addition to the path portion of BaseURL as a parameter passed to HttpClient static method, and register a block for callback.

Figure 2,asi Sample code, initiating an asynchronous request (originating from: ASIHTTPREQUESTTESTS.M)

The use of the ASI recommendation method is very traditional, each request is constructed by the constructor method to initialize a (shared) instance, through this instance configuration parameters and initiate the request. The ASI initially used the delegate mode callback and provided an instance method for registering the block after the iOS SDK supported block.

The two-segment code referenced above is derived from the project's sample project. In contrast to two pieces of code it is clear that the same is the most common asynchronous request, the use of AFN only need to invoke a static method, but the code is less readable, and the ASI example looks clearer, but need to call multiple instance methods to complete a request. AFN's design is more engineered, or more user-friendly, and ASI's design is more classic, typically oop.

In addition to the differences in primary usage, the advanced features and support for extensions are quite different.

2. Advanced Features

AFN only encapsulates a number of common functions to meet basic needs, while ignoring many of the extended features directly. For example: AFN does not encapsulate sync requests by default, and if developers need to use synchronous requests, they need to override the GetPath:parameters:success:failure method to synchronize Afhttprequestoperation While the ASI is directly by invoking a startsynchronous method.

In addition, AFN encapsulates the respective processors for JSON, XML, plist, and image four data structures, and the developer can register the processor in the operations queue and get the formatted data directly in the callback method. In the example project, a JSON processor was used: registering the afjsonrequestoperation in the operations queue.

Figure 3,afn Sample code, initializing the Custom HttpClient (from: AFAPPDOTNETAPICLIENT.M)

The ASI appears to be more primitive in this regard, not specifically packaged for any data type, but with a variety of interfaces and tools for developers to expand themselves. There is another reason why ASI offers more extensions than AFN, which also abstracts many of the internal functions into classes and methods. For example:

Asihttprequestdatacompressor and Asihttprequestdatadecompressor Two classes, only used to compress local files, construct post body and decompress return data, but these two classes are still designed as standalone functions, Provides a way to compress and decompress multiple data structures.

By comparing the advanced features of both and the support for extensions, it can be seen that AFN has achieved 90 points for the primary function (or commonly known as a common function). The invocation is simple enough, the processor is rich enough, and the user can use it to be easy and enjoyable. But it has abandoned the support for advanced features, to meet the more complex needs, it will be a lot of trouble, in this area up to 40 points. The ASI is obviously not content to do the primary function, but in order to provide a richer extensible interface, it also takes some effort to use the primary function. Although the ASI provides a single control that supports Amazon S3 and Rackspace Cloud files, it is basically useless for me to be born under a red flag, so for the support of the primary function ASI can get a 70 point, sacrificing the ease of use of the primary function, in exchange for good extensibility, The use of advanced features is far better than AFN, can also get a 70 points.

From the point of use comparison, there is basically a general understanding of the two projects, and then go deep to see how the performance of the two.

3. Performance Comparison

I separately with AFN and ASI test, the test environment is as follows: IPhone5, Unicom 3G signal full, indoor static state, the request of domestic dual-line machine room stand-alone server, a total of 20 files, each file request 20 times, records from the creation of the request to the full download of the file time-consuming, The results are as follows:

Figure 4,afn Continuous access to 1 ~ 20K files Time consuming

Figure 5,asi Continuous access to 1 ~ 20K files Time consuming

Figure 4 is a AFN record, Green is the longest time in 20 requests, Blue is the shortest time, and yellow is the 18 mean to remove the maximum and minimum values. As you can see from this diagram, the AFN initially created objects for nearly 2.5 seconds, then stabilized, with Jitter at 3K, 7K, 15K, and 20K. Figure 5 is the result of the ASI doing the same test, the first time to create the object nearly 2.25 seconds, slightly better than AFN, also in 5K, 11K, 13K, 14K and 16K some jitter, but the jitter amplitude appears to be less than AFN, visible stability is better.

Below is a comparison of the two test results together, you can more intuitively compare the difference between them.

Figure 6,asi and AFN time-consuming maximum comparison

The comparison of the maximum values in Figure 6 can be seen more clearly in the comparison of the two jitter, the ASI slightly better.

Figure 7,asi and AFN time-consuming minimum comparison

The minimum value comparison of Figure 7 shows that the optimal performance of the ASI appears to be superior to AFN in each test size.

Figure 8,asi and AFN time-consuming averages comparison

Figure 8 shows a comparison of time-consuming averages, which can be more illustrative of the problem. File less than 12K test in the performance advantage of ASI is not very obvious, more than 12K later, the ASI advantage began to clear up, each request is 20% to 30% less than AFN, nearly 0.1 seconds. Also from this diagram can be seen, as the download file becomes larger, the request time is not linear growth, this is because a request is consumed most of the time to establish a connection, and the actual receipt of data only a very little time, this issue is not discussed in this article, so not to say, interested readers can change the HTTP ://segmentfault.com/t/ios further discussion.

4. Principle Analysis

The performance of ASI seems to be better than AFN, and the bottom of the implementation of the two principles to see what is the cause of this gap. ASI is based on the Cfnetwork framework, and AFN based on Nsurl, the bottom-level difference is one of the important reasons for the performance gap.

Diagram 9,asi and AFN and the underlying framework

We know that all network traffic is based on sockets, one socket connecting to another and transmitting data. BSD sockets are the most common type of socket abstraction interface.

The Cfsocket in the Core Foundation framework was developed based on BSD sockets. It almost covers the full functionality of the BSD socket and, more importantly, integrates the socket into the event's processing cycle. The higher-level cfstream in Core founda-tion is a read-write stream support based on cfsocket development.

Cfnetwork is an underlying high-performance network framework based on Cfstream in Core Foundation, which supports the cfhttp of the HTTP protocol by Cfsocketstream, which provides the underlying services, Cfhttpauthentication based on Cfhttp for identity authentication and CFFTP that support FTP protocol.

As shown in 9, ASI is a component based on cfhttp development, and AFN's basic--nsurl is based on cfnetwork development. That is to say, ASI is lower than AFN, which causes the performance gap to a certain extent.

On the other side, although both are implemented using Nsoperation and nsoperationqueue, the underlying differences also lead to very large differences in how they are implemented.

The direct Operation object of ASI ASIHTTPRequest is a subclass of Nsoperation, which implements the Nscopying protocol. Initialize the related properties in the Initialize and Initwithurl: Methods and configure a list of the default values for request-related parameters. In addition, ASIHTTPRequest provides a series of instance methods to configure the request object. On the processing of the asynchronous request, after the initialization of the ASIHTTPRequest object is completed, the object is joined to the shared operations queue in the Startasynchronous method. Thereafter, all operations, including creating Cfhttpmessageref, the primary object that handles the network request (in fact a pointer to the __CFHTTPMESSAGE structure), are done in the child thread to which the ASIHTTPRequest object belongs.

AFN's direct Operation Object Afhttpclient is different from ASI, and is a nsobject subclass that implements Nscoding and nscopying protocols. Afhttpclient is a "tool class" that encapsulates a series of action methods, and the action class that handles the request is a series of separate, nsoperation-encapsulated, afurlconnectionoperation subclasses. The AFN example code uses a static method that uses Dispatch_once () to create a shared instance of the Afhttpclient, which is also the official recommended method of use. In the initialization method for creating Afhttpclient, Operationqueue is created and a series of parameter defaults are set. Create a nsurlrequest in the GetPath:parameters:success:failure method to nsurlrequest the object instance as a parameter, create a nsoperation, And joins the Nsoperationqueue created in the initialization sender. The above operations are done in the main thread. In the Start method of Nsoperation, create a nsurlconnection with the Nsurlrequest object created earlier and open the link.

There are also differences in the processing of asynchronous callbacks, and the ASI takes the Cfhttp request complete, directly callback the ASIHTTPRequest instance method, completing the delegate mode or block mode callback by storing the information recorded by the instance object. The AFN uses the Nsoperation completionblock attribute directly.

These implementations also show that the ASI appears to be more low-level, and does not overuse the API already encapsulated in the cocoa framework, while AFN is more pragmatic, logic is simple and clear, a lot of use of the framework API. This is one of the reasons for the difference in performance.

Summarize

By comparison, it can be said that the AFN is suitable for logic-simple applications, or more suitable for teams that are not yet rich in development resources, because AFN is much more user-friendly than ASI, and such applications (or teams) have a very low level of customization requirements for the underlying network controls. ASI is better suited for applications that have been developing for some time, or for developing resource-rich teams, because often these teams (or their applications) have accumulated some experience, both on the product and on the technical. The complexity of requirements is high up at this time, and the demand for the bottom-line is more and more, at this time AFN is difficult to meet the demand, need to sacrifice a certain ease of use, using ASI as the network underlying control. The Segmentfault open source client is now designed as a simple read client with little customization required, so I currently choose AFN as a network control.

Above the ASI and AFN two most commonly used iOS low-level network control to do a preliminary introduction, to more in-depth understanding of the two controls, but also need to continue to study their own source code. Any technical questions you may have about iOS can be discussed in Http://segmentfault.com/t/ios. In addition, you can continue to focus on Segmentfault's open source client and explore iOS development techniques with more developers.

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.