Objective
Recently, in the book "High-Performance JavaScript" (2010 version Dingchen), it may be because of improvements in the browser engine or other reasons, some of the books have been able to mention high-performance code in the latest browser has been invalidated. But some chapters of some content is quite good, such as the eighth chapter of programming practice, in order to facilitate the future review, to do a summary. The failed code will also be explored further in the future.
Avoid double evaluation
This optimization strategy is well understood, and we may have unwittingly used it in actual programming:
// Not the use of this setTimeout (' Alert (' Hello World ') ', +); // Use the This setTimeout (function() { alert (' Hello World' 1000);
The above two pieces of code can be executed, but we generally use the second, the same for setinterval, similar to the eval () and function () constructors. JavaScript, like many other scripting languages, allows you to extract a string containing code in your program and then execute it dynamically. When you execute another piece of JavaScript code in JavaScript code, it results in a double evaluation of the performance cost, which is evaluated first in a normal way, and then a second evaluation operation is initiated during the execution of the code contained in the string. Therefore, it is not necessary to use eval () and function () Most of the time to avoid using them; As for settimeout and SetInterval, it is recommended that you pass in a function instead of a string as the first argument.
This reminds us of the "and" in PHP, and we try to use ' to refer to the string, the same reason.
Using Object/array Direct Volume
// Use thisvarobj ={name:' Hanzichi ', Age:10};vararr = [0, 1, 2, 3];// not use thisvarobj =NewObject (); Obj.name= ' Hanzichi '; Obj.age= 10;vararr =NewArray (); arr[0] = 0; arr[1] = 1; arr[2] = 2; arr[3] = 3;Don't repeat your work.
Perhaps the most common repetition is browser probing (of course "Don't repeat work" is just a thought, not necessarily for browser probing).
Consider an example of adding an event handler, and the typical cross-browser code is as follows:
function AddHandler (target, EventType, handler) { if (target.addeventlistener) { // DOM2 Events false); Else { // IE target.attachevent (' on ' + EventType, handler); }} function () { console.log (' Hello World ');});
But if a page calls several times to add events to the AddHandler function, each time the browser is judged, but the fact is that each time the results are the same, because the browser does not change, then we can "do not repeat work" to do an optimization strategy.
Lazy loading, also known as lazy loading, lazy loading and so on. lazy loading means no action is taken before the information is used :
functionAddHandler (target, EventType, handler) {if(Target.addeventlistener) {//DOM2 EventsAddHandler =function(target, EventType, handler) {Target.addeventlistener (EventType, Handler,false); }; } Else{//IEAddHandler =function(target, EventType, handler) {target.attachevent (' On ' +EventType, handler); }; } addHandler (target, EventType, handler);} //calledAddHandler (document, ' click ',function() {Console.log (' Hello World ');}); AddHandler (window,' KeyDown ',function() {Console.log (' Key Down ');});
The first time the method is called, it checks and determines which method to use to bind the event handler, and the original function is overwritten with the new function that contains the correct operation. The last step calls the new function (you can also return a new function directly) and passes in the original parameter. Each subsequent call to AddHandler () will no longer be detected because the detection code has been overwritten by the new function.
When a deferred load function is called, the first time is always consumed for a long time, because it must run instrumentation and then call another function to complete the task, but subsequent calls to the function become faster because no further testing is required. Lazy loading is the best choice when a function is not called immediately in the page.
Conditional preloading is detected in advance during script loading without waiting for the function to be called:
var AddHandler = Document.addeventlistener? function Span style= "color: #0000ff;" >false ); }: function (target, EventType, handler) {target.attachevent ( ' on ' + EventType, handler); }; // call AddHandler (document, ' Click ', ' KeyDown ', function () {Console.log ( ' key down '
conditional preloading ensures that all functions consume the same time , at the cost of being instrumented when the script is loaded, rather than after it is loaded. Preloading is useful for situations where a function is about to be used and is frequently present throughout the life cycle of a page.
The common "do not repeat work" also has to do Ajax browser detection, you can think of writing code.
Use the fast part
Use bit arithmetic to accelerate everyone should be familiar with and master:
//Use &1 instead of%2varA = 10;if(A & 1) {// Use this // ...}if(A% of 2) {// not use this // ...}//Use << 1 insteadvarA = 10;varb = a << 1;// Use thisvarb = A * 2;// not use thisvarA = 10;varb = a >> 1;// Use thisvarb = A/2;// not use this
Bit operations can accelerate faster, but also can be used in various algorithms and data structures, such as state compression DP, bitwise DP and so on.
No matter how your JavaScript code is optimized, it will never be faster than the native method provided by the JavaScript engine, because the native part of JavaScript already exists in the browser before you write the code, and is written in the underlying language, such as C + +. This means that these methods are compiled into machine code and become part of the browser.
So try to use some built-in functions or constants, such as those provided by the Math object:
Math.EMath.LN10Math.LN2Math.PIMath.SQRT1_2Math.abs () Math.sin () math.sqrt () ...
Another example is the Selector API, which allows the use of CSS selectors to find DOM nodes. CSS queries are native to JavaScript and are supported by jquery. The jquery engine is widely considered the fastest CSS query engine, but it is still slower than the native method. The average time required for the native Queryselector () and Queryselectorall () methods to complete the task is 10% of the JavaScript-based CSS query. So when native methods are available, use them as much as possible. Especially with math and DOM operations, you can do more with the compiled code, and the faster your code gets.
High performance JavaScript programming practice