Analysis of data access performance optimization in javascript and javascript Performance Optimization
Generally, writing code considers code readability, scalability, and browser parsing. Reducing the number of Code increases the loading speed of code performance, which is what every coder is pursuing. In javascript, we sometimes have to consider how to determine the storage location of data to obtain the best read/write efficiency. The location of data storage is related to the speed at which data is retrieved during code execution, the data storage location will greatly affect the reading speed.
Javascript has four basic Data Access Locations: Direct Volume, variables, array elements, and objects.
Each data storage location has different read/write consumption. In general, the performance of accessing data from a direct volume and a local variable is very small and insignificant. However, the cost for accessing array elements and object members is relatively high, which depends on the browser.
The parsing of identifiers also consumes computer performance. In the running scope, the deeper the location of an identifier, the slower its read/write speed. Therefore, in the function, local variables are the fastest to read and write, while global variables are the slowest to read and write, because global variables are always at the end of the runtime scope chain environment. Therefore, in browsers without optimizing the javascript engine, we try to use local variables. If a cross-scope value is referenced more than once in a function, we can store it in a local variable, example
function initUI(){ var doc = document, bd = doc.body, links= doc.getElementsByTagName('a'), i = 0, len = links.length; while(i<len){ update(links[i++]); } doc.getElementById('btn').onclick=function(){ }; bd.className = 'active'; }
The document object is stored in the local variable doc, and the reference is reduced to once three times. Although the performance improvement is not obvious, if the document global variable is referenced many times, the performance improvement will be obvious.