Home >Web Front-end >JS Tutorial >JavaScript performance optimization tips
JavaScript is already the most popular language at present. It can do many things - website interface, server-side, games, operating systems, robots and many more.
However, to be honest, even though it is so popular, its performance has not yet reached its limit. Yes, it's improving, but until it catches up with native apps in every aspect, you're going to have to use some tricks to optimize its performance when making a HYBIRD app.
Firefox has currently the fastest JavaScript parser SpiderMonkey,
There are various efforts to make JavaScript faster, one of which is asm.js. Asm.js is a subset of JavaScript produced by Emscripten , it does a lot of optimizations for JavaScript code compiled from C/C++. The compiled code is ugly, which is why you can't write the optimized code yourself, but it runs very fast. I suggest you read this article
Stop talking and give me an example!
Okay, our goal is to write faster JavaScript code, here are some tips to make your code run faster, and better memory efficiency. Please note that I'm not strictly talking about the DOM and web applications, it's about JavaScript, of which the DOM is just one part.
Seeing is believing, I want to add the jsperf test case as the first one, using Firefox38 and Chrome39 tests.
#1 Don’t type cast
JavaScript is dynamically typed, but don’t use that feature if you want to increase speed. Try to keep the types of variables consistent. This also applies to arrays, although mostly optimized by browsers, try not to mix arrays of different types. This is one of the reasons why C/C++ code compiled into JavaScript uses static typing.
{ var x = '2'; var y = 5; x = 2; x + y; }
Test case
In addition: Conversion between string and number types
For example, you have to convert a string into a number. Are parseInt and parseFloat the best methods? let's see.
parseFloat("100") +"100" // 整型 parseInt("100", 10) "100"|0 "100" >> 0 "100" << 0 // 仅适用于正数 "100" >>> 0
parseInt test ~ parseFloat test
Firefox is optimized for bitwise operations and runs code about 99% faster than parseInt and + operations. Chrome obviously has no preference for bitwise operators, they are 62% slower than the parseInt function.
parseFloat is faster than the + operator on both browsers (Firefox 28%, Chrome 39%).
So, if you are writing a Node/Chrome or Firefox application? In my opinion, generally using the parseInt function is correct.
#2 Don’t restructure objects
Restructuring objects is not cheap and should be avoided:
Don’t use the delete operator
Deletion operations are much slower than assigning a null property. Assigning null is 99% faster in both browsers, but it cannot modify the structure of the object, but deletion can.
Edit: I think this is a bit misleading, it doesn't mean you shouldn't use the delete operator, the delete operator has its own use case, it can prevent memory leaks of objects.
delete vs null
Don’t add attributes later
Try not to add attributes later, it’s best to define the object’s structure from the beginning. This is 100% faster in Firefox and 89% faster in Chrome.
Dynamic attributes VS pre-defined structures
#3 String concatenation
String concatenation is a very expensive operation, but what method should be used? Certainly not Array.prototype.join.
The += operator seems to be much faster than +, String.prototype.concat and Array.prototype.join are faster in both browsers. Array.prototype.join is the slowest, in line with market expectations.
String concatenation testing
#4 Correct use of regular expressions
Using RegExp.prototype.exec is not necessary, is it?
However, there is a performance difference between RegExp.prototype.test and String.prototype.search, let’s see which method is faster:
Regular expression method
RegExp.prototype.exec than String. prototype.match is a lot faster, but they are not exactly the same thing, and their differences are beyond the scope of this article. See this Q&A.
RegEx.prototype.test is faster, probably because it does not return the index where the match was found. String.prototype.search should only be used to find the required matching index.
However, you should not use regular expressions to find the position of another string, you can use the String.prototype.indexOf method.
String.prototype.search VS String.prototype.indexOf
另一个有趣的基准是String.prototype.indexOf VS RegExp.prototype.test,我个人预计后者要快,这是在Firefox中发生的事情,但在Chrome中,事实并非如此。 RegExp.prototype.test在Firefox中快32%,而在Chrome中String.prototype.indexOf快33%。在这种情况下,你自己选择喜欢的方式吧。
#5限制声明/传递变量的范围(作用域)
假如你调用一个函数,浏览器必须做一些所谓的范围查找,它的昂贵程度取决于它要查找多少范围。尽量不要依辣全局/高范围的变量,尽量使局部范围变量,并将它们传递给函数。更少的范围查找,更少的牺牲速度。
这个测试告诉我们,从局部范围内传递和使用变量比从更高的声明范围查找变量快,无论是Chrome和Firefox。
内部范围VS高范围VS全局
#6你不需要所有的东西都用jQuery
大多数开发者使用jQuery做一些简单的任务,我的意思在一些场合你没有必要使用jQuery,你觉得用$.val()始终是必要的吗?就拿这个例子:
$('input').keyup(function() { if($(this).val() === 'blah') { ... } });
这是学习如何使用JavaScript修改DOM的最重要原因之一,这样你可以编写更高效的代码。
用纯JavaScript100%完成同样的功能100%的速度更快,这是JSPerf基准测试
$('input').keyup(function() { if(this.value === 'blah') { ... } });