Table of Contents
Pay attention to scope
Choose the right method
最小化语句数
优化DOM交互
Home Web Front-end JS Tutorial JavaScript best practices in detail – Performance

JavaScript best practices in detail – Performance

Mar 07, 2017 pm 03:04 PM

Pay attention to scope

Avoid global search

An example:

function updateUI(){
    var imgs = document.getElementByTagName("img");
    for(var i=0, len=imgs.length; i<len; i++){
        imgs[i].title = document.title + " image " + i;
    }
    var msg = document.getElementById("msg");
    msg.innnerHTML = "Update complete.";
}
Copy after login

This function may look completely normal, but it contains three A reference to the global document object. If there are multiple images on the page, the document reference in the for loop will be executed multiple times or even hundreds of times, and a scope chain search will be performed each time. By creating a local variable pointing to the document object, you can improve the performance of this function by limiting a global search:

function updateUI(){
    var doc = document;
    var imgs = doc.getElementByTagName("img");
    for(var i=0, len=imgs.length; i<len; i++){
        imgs[i].title = doc.title + " image " + i;
    }
    var msg = doc.getElementById("msg");
    msg.innnerHTML = "Update complete.";
}
Copy after login

Here, first store the document object in the local doc variable; then in the remaining code Replace the original document. Compared to the original version, the function now only has one global lookup, which is definitely faster.

Choose the right method

1. Avoid unnecessary attribute lookups

Getting constant values ​​is a very efficient process

var value = 5;
var sum = 10 + value;
alert(sum);
Copy after login

The code does four constant value lookups: the number 5, the variable value, the number 10, and the variable sum.

Accessing array elements in JavaScript is as efficient as simple variable lookup. So the following code is as efficient as the previous example:

var value = [5,10];
var sum = value[0] + value[1];
alert(sum);
Copy after login

Any property lookup on the object will take longer than accessing a variable or array, because a search for the property with that name must be done in the prototype chain . The more attribute lookups there are, the longer the execution time will be.

var values = {first: 5, second: 10};
var sum = values.first + values.second;
alert(sum);
Copy after login

This code uses two attribute lookups to calculate the value of sum. Doing an attribute lookup once or twice won't cause significant performance issues, but doing it hundreds or thousands will definitely slow down execution.

Pay attention to multiple attribute lookups that obtain a single value. For example:

var query = window.location.href.substring(window.location.href.indexOf("?"));
Copy after login

In this code, there are 6 attribute lookups: 3 times for window.location.href.substring(), and 3 times for window.location.href.indexOf(). Just count the number of points in the code to determine the number of searches. This code uses window.location.href twice, and the same search is performed twice, so the efficiency is particularly poor.

Once an object property is used multiple times, it should be stored in a local variable. The previous code can be rewritten as follows:

var url = window.locaiton.href;
var query = url.substring(url.indexOf("?"));
Copy after login

This version of the code has only 4 attribute lookups, which saves 33% compared to the original version.

Generally speaking, as long as it can reduce the complexity of the algorithm, it should be reduced as much as possible. Use local variables to replace property lookups with value lookups as much as possible, and furthermore, use numeric locations if they can be accessed either with numeric array locations or with named properties (such as NodeList objects).

2. Optimize loop

The basic optimization steps of a loop are as follows.

(1) Decrement iteration - Most loops use an iterator that starts at 0 and increases to a specific value. In many cases, it is more efficient to decrement an iterator through the loop, starting from the maximum value.

(2) Simplify the termination condition - Since each loop process will calculate the termination condition, it must be guaranteed to be as fast as possible. This means avoiding property lookups or other operations.

(3) Simplify the loop body - the loop is the most executed, so make sure it is optimized to the maximum extent and ensure that some other intensive calculations of the loop can be easily removed.

(4 Use post-test loops - the most commonly used for loops and while loops are pre-test loops. Post-test loops such as do-while can avoid the calculation of the initial termination condition, so it runs faster .

The following is a basic for loop:

for(var i=0; i < value.length; i++){
    process(values[i]);
}
Copy after login

In this code, the variable i is incremented from 0 to the total number of elements in the values ​​array, and the loop can be changed to decrement i, as shown below. :

for(var i=value.length -1; i >= 0; i--){
    process(values[i]);
}
Copy after login

The termination condition is simplified from value.length to 0.

The loop can also be changed into a post-test loop, as follows:

var i=values.length -1;
if (i> -1){
    do{
        process(values[i])
    }while(--i>=0) //此处有个勘误,书上终止条件为(--i>0),经测试,(--i>=0)才是正确的
}
Copy after login

The main optimization here is The termination condition and the decrement operator are combined into a single statement, and the loop part has been fully optimized.

Remember that when using a "post-test" loop, you must ensure that there is at least one value to be processed. An empty array will result. The extra loop can be avoided with the "pre-test" loop

3. Unroll the loop

When the number of loops is determined, eliminate the loop and use it multiple times. Function calls are often faster. Assuming there are only 3 elements in the values ​​array, calling process() directly on each element can eliminate the additional overhead of setting up the loop and processing the termination condition, making the code run faster.

If the number of iterations in the loop cannot be determined in advance, you can consider using a technique called a Duff device. The basic concept of a Duff device is to expand a loop into a series of statements by calculating whether the number of iterations is a multiple of 8.

Andrew B. King proposed a faster Duff device technique by splitting the do-while loop into 2 separate loops. Here is an example:

//消除循环
process(values[0]);
process(values[1]);
process(values[2]);
Copy after login

In this implementation, the remaining The calculation part is not processed in the actual loop, but is divided by 8 in an initialization loop. When the extra elements are processed, the main loop continues with 8 calls to process()

#. ##Using unrolled loops for large data sets can save a lot of time, but for small data sets, the additional overhead may not be worth the gain. It requires more code to complete the same task. Generally, if the data set is not processed. It's not worth it.

4.避免双重解释

当JavaScript代码想解析KavaScript的时候就会存在双重解释惩罚。当使用eval()函数或者是Function构造函数以及使用setTimeout()传一个字符串参数时都会发生这种情况。

//某些代码求值——避免!!
eval("alert(&#39;Hello world!&#39;)");

//创建新函数——避免!!
var sayHi = new Function("alert(&#39;Hello world!&#39;)");

//设置超时——避免!!
setTimeout("alert(&#39;Hello world!&#39;)", 500);
Copy after login

在以上这些例子中,都要解析包含了JavaScript代码的字符串。这个操作是不能在初始的解析过程中完成的,因为代码是包含在字符串中的,也就是说在JavaScript代码运行的同时必须新启动一个解析器来解析新的代码。实例化一个新的解析器有不容忽视的开销,所以这种代码要比直接解析慢得多。

//已修正
alert(&#39;Hello world!&#39;);

//创建新函数——已修正
var sayHi = function(){
    alert(&#39;Hello world!&#39;);
};

//设置一个超时——已修正
setTimeout(function(){
    alert(&#39;Hello world!&#39;);
}, 500);
Copy after login

如果要提高代码性能,尽可能避免出现需要按照JavaScript解析的字符串。

5.性能的其他注意事项

(1)原生方法较快

(2)Switch语句较快

(3)位运算符较快

最小化语句数

1.多个变量声明

//4个语句——很浪费
var count = 5;
var color = "blue";
var values = [1,2,3];
var now = new Date();

//一个语句
var count = 5,
    color = "blue",
    values = [1,2,3],
    now = new Date();
Copy after login

2.插入迭代值

当使用迭代值的时候,尽可能合并语句。

var name = values[i];
i++;
Copy after login

前面这2句语句各只有一个目的:第一个从values数组中获取值,然后存储在name中;第二个给变量i增加1.这两句可以通过迭代值插入第一个语句组合成一个语句。

var name = values[i++];
Copy after login

3.使用数组和对象字面量

//用4个语句创建和初始化数组——浪费
var values = new Array();
values[0] = 123;
values[1] = 456;
values[2] = 789;

//用4个语句创建和初始化对象——浪费
var person = new Object();
person.name = "Nicholas";
person.age = 29;
person.sayName = function(){
    alert(this.name);
};
Copy after login

这段代码中,只创建和初始化了一个数组和一个对象。各用了4个语句:一个调用构造函数,其他3个分配数据。其实可以很容易地转换成使用字面量的形式。

//只有一条语句创建和初始化数组
var values = [13,456,789];

//只有一条语句创建和初始化对象
var person = {
    name : "Nicholas",
    age : 29,
    sayName : function(){
        alert(this.name);
    }
};
Copy after login

重写后的代码只包含两条语句,减少了75%的语句量,在包含成千上万行JavaScript的代码库中,这些优化的价值更大。
只要有可能,尽量使用数组和对象的字面量表达方式来消除不必要的语句。

优化DOM交互

1.最小化现场更新

一旦你需要访问的DOM部分是已经显示的页面的一部分,那么你就是在进行一个现场更新。现场更新进行得越多,代码完成执行所花的事件就越长。

var list = document.getElementById(&#39;myList&#39;),
    item,
    i;
for (var i = 0; i < 10; i++) {
    item = document.createElement("li");
    list.appendChild(item);
    item.appendChild(document.createTextNode("Item" + i));
}
Copy after login

这段代码为列表添加了10个项目。添加每个项目时,都有2个现场更新:一个添加li元素,另一个给它添加文本节点。这样添加10个项目,这个操作总共要完成20个现场更新。

var list = document.getElementById(&#39;myList&#39;),
    fragment = document.createDocumentFragment(),
    item,
    i;
for (var i = 0; i < 10; i++) {
    item = document.createElement("li");
    fragment.appendChild(item);
    item.appendChild(document.createTextNode("Item" + i));
}
list.appendChild(fragment);
Copy after login

在这个例子中只有一次现场更新,它发生在所有项目都创建好之后。文档片段用作一个临时的占位符,放置新创建的项目。当给appendChild()传入文档片段时,只有片段中的子节点被添加到目标,片段本身不会被添加的。

一旦需要更新DOM,请考虑使用文档片段来构建DOM结构,然后再将其添加到现存的文档中。

2.使用innerHTML

有两种在页面上创建DOM节点的方法:使用诸如createElement()和appendChild()之类的DOM方法,以及使用innerHTML。对于小的DOM更改而言,两种方法效率都差不多。然而,对于大的DOM更改,使用innerHTML要比使用标准DOM方法创建同样的DOM结构快得多。

当把innerHTML设置为某个值时,后台会创建一个HTML解析器,然后使用内部的DOM调用来创建DOM结构,而非基于JavaScript的DOM调用。由于内部方法是编译好的而非解释执行的,所以执行快得多。

var list = document.getElementById("myList");
    html = "";
    i;

for (i=0; i < 10; i++){
    html += "<li>Item " + i +"</li>";
}
list.innerHTML = html;
Copy after login

使用innerHTML的关键在于(和其他的DOM操作一样)最小化调用它的次数。

var list = document.getElementById("myList");
    i;

for (i=0; i < 10; i++){
    list.innerHTML += "<li>Item " + i +"</li>";  //避免!!!
}
Copy after login

这段代码的问题在于每次循环都要调用innerHTML,这是极其低效的。调用innerHTML实际上就是一次现场更新。构建好一个字符串然后一次性调用innerHTML要比调用innerHTML多次快得多。

3.使用事件代理(根据第13章的概念,我认为此处应为“事件委托”更为妥当)

4.注意HTMLCollection

任何时候要访问HTMLCollection,不管它是一个属性还是一个方法,都是在文档上进行一个查询,这个查询开销很昂贵。

var images = document.getElementsByTagName("img"),
    image,
    i,len;

for (i=0, len=images.length; i < len; i++){
    image = images[i];
    //处理
}
Copy after login

将length和当前引用的images[i]存入变量,这样就可以最小化对他们的访问。发生以下情况时会返回HTMLCollection对象:

  • 进行了对getElementsByTagName()的调用;

  • 获取了元素的childNodes属性;

  • 获取了元素的attributes属性;

  • 访问了特殊的集合,如document.forms、document.images等。

 以上就是详细介绍JavaScript最佳实践 –性能的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Comparing the performance of Win11 and Win10 systems, which one is better? Comparing the performance of Win11 and Win10 systems, which one is better? Mar 27, 2024 pm 05:09 PM

The Windows operating system has always been one of the most widely used operating systems on personal computers, and Windows 10 has long been Microsoft's flagship operating system until recently when Microsoft launched the new Windows 11 system. With the launch of Windows 11 system, people have become interested in the performance differences between Windows 10 and Windows 11 systems. Which one is better between the two? First, let’s take a look at W

Windows 10 vs. Windows 11 performance comparison: Which one is better? Windows 10 vs. Windows 11 performance comparison: Which one is better? Mar 28, 2024 am 09:00 AM

Windows 10 vs. Windows 11 performance comparison: Which one is better? With the continuous development and advancement of technology, operating systems are constantly updated and upgraded. As one of the world's largest operating system developers, Microsoft's Windows series of operating systems have always attracted much attention from users. In 2021, Microsoft released the Windows 11 operating system, which triggered widespread discussion and attention. So, what is the difference in performance between Windows 10 and Windows 11? Which

Kirin 8000 processor competes with Snapdragon series: Who can be king? Kirin 8000 processor competes with Snapdragon series: Who can be king? Mar 25, 2024 am 09:03 AM

In the era of mobile Internet, smartphones have become an indispensable part of people's daily lives. The performance of smartphones often directly determines the quality of user experience. As the &quot;brain&quot; of a smartphone, the performance of the processor is particularly important. In the market, the Qualcomm Snapdragon series has always been a representative of strong performance, stability and reliability, and recently Huawei has also launched its own Kirin 8000 processor, which is said to have excellent performance. For ordinary users, how to choose a mobile phone with strong performance has become a key issue. Today we will

The local running performance of the Embedding service exceeds that of OpenAI Text-Embedding-Ada-002, which is so convenient! The local running performance of the Embedding service exceeds that of OpenAI Text-Embedding-Ada-002, which is so convenient! Apr 15, 2024 am 09:01 AM

Ollama is a super practical tool that allows you to easily run open source models such as Llama2, Mistral, and Gemma locally. In this article, I will introduce how to use Ollama to vectorize text. If you have not installed Ollama locally, you can read this article. In this article we will use the nomic-embed-text[2] model. It is a text encoder that outperforms OpenAI text-embedding-ada-002 and text-embedding-3-small on short context and long context tasks. Start the nomic-embed-text service when you have successfully installed o

Comparison of PHP and Go languages: big performance difference Comparison of PHP and Go languages: big performance difference Mar 26, 2024 am 10:48 AM

PHP and Go are two commonly used programming languages, and they have different characteristics and advantages. Among them, performance difference is an issue that everyone is generally concerned about. This article will compare PHP and Go languages ​​from a performance perspective, and demonstrate their performance differences through specific code examples. First, let us briefly introduce the basic features of PHP and Go language. PHP is a scripting language originally designed for web development. It is easy to learn and use and is widely used in the field of web development. The Go language is a compiled language developed by Google.

Performance comparison of different Java frameworks Performance comparison of different Java frameworks Jun 05, 2024 pm 07:14 PM

Performance comparison of different Java frameworks: REST API request processing: Vert.x is the best, with a request rate of 2 times SpringBoot and 3 times Dropwizard. Database query: SpringBoot's HibernateORM is better than Vert.x and Dropwizard's ORM. Caching operations: Vert.x's Hazelcast client is superior to SpringBoot and Dropwizard's caching mechanisms. Suitable framework: Choose according to application requirements. Vert.x is suitable for high-performance web services, SpringBoot is suitable for data-intensive applications, and Dropwizard is suitable for microservice architecture.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

What impact do C++ functions have on program performance? What impact do C++ functions have on program performance? Apr 12, 2024 am 09:39 AM

The impact of functions on C++ program performance includes function call overhead, local variable and object allocation overhead: Function call overhead: including stack frame allocation, parameter transfer and control transfer, which has a significant impact on small functions. Local variable and object allocation overhead: A large number of local variable or object creation and destruction can cause stack overflow and performance degradation.

See all articles