JS's efficiency considerations and choices for compatibility methods

Source: Internet
Author: User

Today I read a book to write an example, encountered a problem.

Because array.every is a method defined by ECMAScript 5, browser versions supported by IE +, FireFox, Opera 9.5+, Safari and chrome* are required, compatibility is required when considering compatibility :

 // definition mode 1 
varHS = { //This is an array of tool classes used to write compatibility methodsArrayutil: {every:function(arr, func) {//The detection of parameters is omitted ... if(array.every) {//preferential use of native methods returnArr.every (func); } Else{//Otherwise, use the compatibility method varresult =false; for(varI=0,len=arr.length; i<len; i++) {result=func (Arr[i], I, arr); if(Result = = =false) { return false; } } return true; } } //other compatibility methods omitted ... }}

This enables compatibility with low-version browsers such as IE6.

But this definition means that the every method has a problem that it repeats itself every time it is invoked-does the browser support the native array.every? Does the browser support native Array.every? Does the browser support native Array.every? ...... Even if you always get the same answer ...

If this compatibility method is only called occasionally, then repeated judgments are not a big problem.

But if this method is frequently called, the performance waste caused by repeated judgments cannot be overlooked.

Then there is the following definition:

 // definition mode 2 
varHS ={arrayutil: {every:function () { // This is a self-tuning function that makes compatibility judgments at the creation of the (object) method, leaving only one selection, which forms the entire contents of the Every method. if(array.every) { retrun function (arr, func) {returnArr.every (func); // The original execution code is wrapped in the function, and this function will be returned by the self-tuning function and assigned to every.   }; } Else { return function (arr, func) {varresult =false; for(varI=0,len=arr.length; i<len; i++) {result=func (Arr[i], I, arr); if(Result = = =false) { return false; } } return true; }; } }() }}

In this way, only one judgement will be made once when the object (method) is created, and every retains the only method that will not repeat and make no sense when the call is executed.

This approach makes the program more concise and faster (even if it's just a little bit, but this is the amount of accumulation).

However, it is not completely flawed, and its problems are reflected when the code is first loaded (or program initialized):

If it is a personal website, lightweight code, its "one step" advantages will be revealed undoubtedly;

But in the face of large web portals such as the portal, in the face of a large number of code (need to make a lot of compatibility judgment), its "one-time" will make your program execution appear procrastination and difficulty.

Fortunately, this problem is not unavoidable, we can "shunt" the program Processing: The compatibility method in the program or the use of a one-time judgment, but this "disposable" no longer get together in the program initialization, but shunt in the method initial call-when the method is explicitly called when the only time to judge.

//definition Mode 3varHS ={arrayutil: {every:function(arr, func) {if(array.every) {this.every = function (arr, func) {        //re-assign value                    returnArr.every (func);            }; } Else {                this.every = function (arr, func) {        //re-assign value                    varresult =false;  for(varI=0,len=arr.length; i<len; i++) {result=func (Arr[i], I, arr); if(Result = = =false) {                            return false; }                    }                    return true;            }; }            return This.every (arr, func);                    //method is first called and re-assigned to execute once, ensuring that the first call can have a result.         }    }}    

This solves the problem, only when the method is used to make a judgment, does not affect the object construction, program initialization speed.

This approach also loses some performance in the first invocation of the method, compared to the second, but is the best option for the performance of the entire program.

Three ways to define each have advantages and disadvantages, different use of the environment:

Compatibility method occasionally used, option 1

The compatibility method is used frequently, but the quantity is small, choose the way 2

The compatibility method is frequently used, and the quantity is large, select mode 3

In addition, in all cases can be good and safe, is the way 3

JS's efficiency considerations and choices for compatibility methods

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.