вторник, 29 июля 2014 г.

Совет по написанию быстрого JavaScript

Be wary of multiple property lookups to retrieve a single value. For example, consider the following:
var query = window.location.href.substring(window.location.href.indexOf("?"));
In this code, there are six property lookups: three for window.location.href.substring() and
three for window.location.href.indexOf(). You can easily identify property lookups by counting
the number of dots in the code. This code is especially inefficient because the window.location.href value is being used twice, so the same lookup is done twice.
Whenever an object property is being used more than once, store it in a local variable. You’ll still
take the initial O(n) hit to access the value the fi rst time, but every subsequent access will be O(1),
which more than makes up for it. For example, the previous code can be rewritten as follows:
var url = window.location.href;
var query = url.substring(url.indexOf("?"));
This version of the code has only four property lookups, a savings of 33 percent over the original.
Making this kind of optimization in a large script is likely to lead to larger gains.

Комментариев нет:

Отправить комментарий