Function. apply () parameter array is used to improve JavaScript program performance. javascriptapply

Source: Internet
Author: User

Function. apply () parameter array is used to improve JavaScript program performance. javascriptapply

Let's talk about Function. apply () in improving program performance.

Let's start with the Math. max () function. Math. max can be followed by any parameter and return the maximum value among all parameters.

For example

alert(Math.max(5,8))   //8  alert(Math.max(5,7,9,3,1,6))   //9  

However, in many cases, we need to find the largest element in the array.

Var arr = [5, 7, 9, 1] alert (Math. max (arr) // This is not acceptable. Be sure to write function getMax (arr) {var arrLen = arr. length; for (var I = 0, ret = arr [0]; I <arrLen; I ++) {ret = Math. max (ret, arr [I]);} return ret ;}

 

This is troublesome and inefficient. If you use apply, check the Code:

function getMax2(arr){      return Math.max.apply(null,arr)  }  

 


The two pieces of code achieve the same purpose, but getMax2 is elegant, efficient, and concise.

Performance test:
GetMax performance test

Var myArr = new Array () function fillRnd (arrLen) {// enter random numbers from 1 to 10 in arrLen to the Array for (var I = 0, arr = []; I <arrLen; I ++) {arr [I] = Math. ceil (Math. random () * 10)} return arr} function getMax (arr) {var arrLen = arr. length; for (var I = 0, ret = arr [0]; I <arrLen; I ++) {ret = Math. max (ret, arr [I]);} return ret;} function getMax2 (arr) {return Math. max. apply (null, arr)} myArr = fillRnd (20*10000) // generate 0.2 million random numbers and fill in the array var t1 = new Date () var Max1 = getMax (myArr) var t2 = new Date () var max2 = getMax2 (myArr) var t3 = new Date () if (max1! = Max2) alert ("error") alert ([t3-t2, t2-t1]) // 96,464 on my machine. Different machines may have different results

 


By comparing 0.2 million pieces of data, the getMax2 time is 96 ms while the getmax time is 464. The difference is 5 times


Another example is the array push method.

var arr1=[1,3,4];  var arr2=[3,4,5];  

If we want to expand arr2, append it to arr1 one by one, and finally let arr1 = [1, 3, 4, 5]

Arr1.push (arr2) obviously does not work. In this case, [, 4, [, 5] is obtained.

 

We can only use one loop to push one by one (of course, we can also use arr1.concat (arr2), but the concat method does not change the arr1 itself)

var arrLen=arr2.length  for(var i=0;i<arrLen;i++){      arr1.push(arr2[i])  } 

 

With Apply, things have become so simple.

Array.prototype.push.apply(arr1,arr2)

 

How to optimize the performance of JavaScript scripts
Posted by ShiningRay on April 5 th, 2006

Author: ShiningRay @ Nirvana Studio
With the development of the network, network speed and machine speed, more and more websites use a variety of client technologies. Ajax is currently the most popular method. JavaScript is an interpreted language, so it cannot reach the level of C/Java, which limits what it can do on the client. In order to improve its performance, I want to talk about my experience based on the many tests I have done for JavaScript before, hoping to help you improve your JavaScript script performance.
Language hierarchy
Loop
Loop is a commonly used control structure. Most things are completed by it. in JavaScript, we can use for (;), while (), for (in) in fact, the efficiency of for (in) in these three loops is very poor, because it needs to query hash keys, as long as it can be used as little as possible. The performance of for (;) and while loops is equivalent to that of normally used loops.
In fact, how to use these two cycles is very important. For some interesting cases during the test, see the appendix. The final conclusion is:
If it is a loop variable that increments or decreases, do not assign values to the loop variable separately. You should use nested ++ or-operators during the last read.
If you want to compare the length of the array, you should first put the length attribute of the array into a local variable to reduce the number of queries.
Local and global variables
Local variables are faster than global variables, because global variables are actually members of global objects, and local variables are placed in the function stack.
Do not use Eval
Using eval is equivalent to calling the interpretation engine again at runtime to run the content, which consumes a lot of time. At this time, the closure supported by JavaScript can be used to implement the function template (for details about the closure, refer to the relevant content of functional programming)
Reduce Object Search
A. b. c. d. e. You must perform at least four query operations. Check a first, then B in a, and then c in B. So if such expressions repeat, you should try to avoid such expressions as long as possible. You can use local variables to put them in a temporary place for query.
This can be combined with loops, because we often need to loop based on the length of strings and arrays, And the length is usually unchanged, for example, each query. length, an additional operation is required, and var len =. length, then one query is missing.
String connection
If it is an append string, it is best to use the s + = anotherStr operation instead of the s = s + anotherStr operation.
To connect multiple strings, use less + =, as shown in figure
S + = a; s + = B; s + = c; it should be written
S + = a + B + c; if it is a collection string, such as multiple operations on the same string + =, it is best to use a cache. How to use it? Use JavaScript Arrays for collection, and connect using the join method, as shown below:
Var buf = new Array (); for (var I = 0; I <100; I ++) {buf. push (I. toString ();} var all = buf. join (""); type conversion
Type conversion is a common mistake because JavaScript is a dynamic type language and you cannot specify the type of a variable.
1. Convert the number into a string and apply "" + 1. Although it looks ugly, the efficiency is actually the highest. In terms of performance:
("" +)> String ()>. toString ()> new String ()
This is actually a bit similar to the following "Direct Volume". The internal operations that can be used during compilation are faster than those used during running.
String () is an internal function, so the speed is very fast, and. toString () is used to query functions in the prototype, so the speed is inferior. new String () is used to return an exact copy.
2. converting a floating point to an integer is more prone to errors. Many people prefer parseInt (). In fact, parseInt () is used to convert a string to a number, rather than converting between a floating point and an integer, we should use Math. floor () or Math. round ().
In addition, Math is an internal object, which is different from the problem in Object Search in section 2. Therefore, Math. floor () does not actually have many query methods and call times, and the speed is the fastest.
3. for custom objects, if the toString () method is defined for type conversion, we recommend that you explicitly call toString (), because after all the possibilities of internal operations are attempted, will try to convert the toString () method of the object to String, so it is more efficient to directly call this method.
Direct usage
In fact, this effect is relatively small and can be ignored. For example, JavaScript supports the use of [param,...] in the past, we used new Array (param, param ,...), the former is directly explained by the engine, and the latter calls an Array internal constructor, so it is a little faster.
Similarly, var foo = {} is faster than var foo = new Object (); and var reg =/.../; is faster than var reg = new RegExp.
String Traversal
Regular expressions should be used for loop operations on strings, such as replacement and search, because JavaScript itself is slow in the cycle, while regular expression operations are performed using APIs written in C language, good performance.
Advanced object
Custom advanced objects and Date and RegExp objects consume a lot of time during construction. If reusable, cache should be used.
DOM-related
Insert HTML
Many users prefer to use document. write in JavaScript to generate content for pages. In fact, this is less efficient. If you need to insert HTML directly, you can find a container element, such as specifying a div or span, and set their innerHTML to insert their HTML code into the page.
Object Query
Use [""] to query. items () is faster, which is the same as the previous idea of reducing object search. items () adds a query and function call.
Create a DOM Node
Generally, we may use strings to directly write HTML to create nodes.
Code validity cannot be guaranteed
Low string operation efficiency
So we should use document. createElement () method. If there is a ready-made template node in the document, you should use the cloneNode () method. Because after using the createElement () method, you need to set attributes of multiple elements, using cloneNode () can reduce the number of attribute settings-if you need to create many elements, you should first prepare a template node.
Timer
If you are targeting constantly running code, you should not use setTimeout, but setInterval. SetTimeout you need to reset a timer each time.
Others
Script Engine
According to my test, Microsoft's JScript is much less efficient than Mozilla's Spidermonkey, whether it is execution speed or memory management, because JScript is not updated now. However, SpiderMonkey cannot use ActiveXObject.
File Optimization
File optimization is also an effective method. Deleting all spaces and comments and placing the code in one line can speed up the download process. Note that the download speed is not the resolution speed, if it is local, comments and spaces do not affect the speed of interpretation and execution.
Summary
This article summarizes some methods I have found in JavaScript programming to improve the JavaScript running performance. In fact, these experiences are based on several principles:
Taking the ready-made items directly is faster, for example, local variables are faster than global variables, and the direct amount is faster than the constructed object at runtime.
Reduce execution times as little as possible. For example, You Need To Cache multiple queries first.
Try to use the built-in functions of the language, such as string link.
Use the APIS provided by the system as much as possible because these APIs are compiled binary code with high execution efficiency.
At the same time, some basic algorithm optimizations can also be used in JavaScript. For example, the adjustment of the computing structure will not be repeated here. However, JavaScript is interpreted and generally does not optimize bytecode during runtime. Therefore, these optimizations are still very important.
Of course, some of the skills here are also used in other explanatory languages for your reference.
Reference
Test and comparison of various http://www.umsu.de/jsperf/ browsers
Http://home.earthlink.net /~ Kendrasg/info/js_opt/
Appendix 1
The test code is incomplete due to previous tests. I have added the following parts:

var print;    if(typeof document != "undefined" ){      print = function(){  document.write(arguments[0]);  }  }else if(typeof WScript != "undefined" ){      print = function(){          WScript.Echo(arguments[0],arguments[1],arguments[2]);      }  }    function empty(){  }    function benchmark(f){      var i = 0;      var start = (new Date()).getTime();        while(i < pressure){          f(i++);      }      var end = (new Date()).getTime();      WScript.Echo(end-start);  }    /* i=0 start = (new Date()).getTime(); while(i < 60000){     c = [i,i,i,i,i,i,i,i,i,i];     i++; } end = (new Date()).getTime(); WScript.Echo(end-start); i=0 start = (new Date()).getTime(); while(i < 60000){     c = new Array(i,i,i,i,i,i,i,i,i,i);     i++; } var end = (new Date()).getTime(); WScript.Echo(end-start); */    function internCast(i){      return "" + i;  }    function StringCast(i){      return String(i)  }  function newStringCast(i){      return new String(i)  }  function toStringCast(i){      return i.toString();  }  function ParseInt(){      return parseInt(j);  }  function MathFloor(){      return Math.floor(j);  }  function Floor(){      return floor(j);  }  var pressure = 50000;  var a = "";  var floor = Math.floor;  j = 123.123;  print("-------------\nString Conversion Test");  print("The empty:", benchmark(empty));  print("intern:", benchmark(internCast));  print("String:");  benchmark(StringCast);  print("new String:");  benchmark(newStringCast);  print("toString:");  benchmark(toStringCast);  print("-------------\nFloat to Int Conversion Test");  print("parseInt");  benchmark(ParseInt);  print("Math.floor");  benchmark(MathFloor);  print("floor")  benchmark(Floor);    function newObject(){      return new Object();  }    function internObject(){      return {};  }  print("------------\nliteral Test");  print("runtime new object", benchmark(newObject));  print("literal object", benchmark(internObject));  

 

Appendix 2
Code 1:

    for(var i=0;i<100;i++){          arr[i]=0;      }

 

Code 2:

    var i = 0;      while(i < 100){          arr[i++]=0;      } 

 

Code 3:

    var i = 0;      while(i < 100){          arr[i]=0;          i++;      }  

 

Test the two pieces of code in firefox. The result is that code 2 is better than code 1 and 3, while code 1 is generally better than code 3 and sometimes exceeds code 3. in IE 6.0, code 2 and 3 are sometimes better than code 1 when the test is under great pressure (for example, more than 10000 tests), and sometimes code 1 is far behind, code 2> code 3> code 1 when the test stress is low (for example, 5000 times.
Code 4:

    var i = 0;      var a;      while(i < 100){          a = 0;          i++;      } 

 

Code 5:

    var a;      for(var i=0;i<100;i++){          a = 0;      }

The test results of the above two pieces of code in Firefox and IE are similar in performance.

Code 6:

    var a;      var i=0;      while(i<100){          a=i;          i++;      }

 

Code 7:

    var a;      var i=0;      while(i<100){          a=i++;      } 

 

Code 8:

    var a;      for(var i=0;i<100;i++){          a = i;      }

 

Code 9:

    var a;      for(var i=0;i<100;){          a = i++;      }

These four pieces of code have similar performance in Firefox 6 and 8, while 7 and 9 have similar performance, while 6 and 8 <7, 9;

Finally, let's look at the empty loop.
Code 10:

for(var i=0;i<100;i++){   } 

 

Code 11:

    var i;      while(i<100){        i++;    } 

 


The last test showed a magical result. The time spent on code 10 in Firefox and the time spent on Code 11 were about. Therefore, it does not have reference value, so I did not show it to you at the beginning.

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.