JavaScript code specifications and performance finishing
-
Performance
There are many things to pay attention to in terms of performance of Js:
-
Avoid global lookup
The most important thing to optimize Js performance is to pay attention to the global search, because the scope search is to first search the local scope, and then go to the upper level scope to search until the global scope is not found, so the performance consumption of the global scope search must be higher than The local scope of this function consumes a lot of money. for example:
function setInnerHtml(){ var pDom=doucument.getElementsByTagName(“p”); for(var i=0,len=pDom.lemgth;i<len> <p> </p> <p style="margin-left:30px;"> This code calls document.getElementByid("dom") in a loop, and the document is only executed once outside the loop, so there is no need to assign the document to a local variable. Instead, assign the value inside the loop to a local variable, so there is no need to re-enter the loop each time. To find the global document object. </p> <pre class="brush:php;toolbar:false">function setInnerHtml(){ var domhtml= doucument.getElementByid(“dom”).innerHtml; var pDom=doucument.getElementsByTagName(“p”); for(var i=0,len=pDom.lemgth;i<len> <p> </p> <p style="margin-left:30px;"> The principle is that when the global object is called multiple times, especially in a loop, the global object is finally assigned to the local variable. Of course, the performance difference will not be obvious after dozens of calls, but as a programmer, since Performance-optimized writing should be done as much as possible. </p> <ul class=" list-paddingleft-2"> <li> <p> Avoid with statements </p> </li> </ul> <p style="margin-left:30px;"> This statement is rarely used nowadays, so I won’t say more about it. </p> <ul class=" list-paddingleft-2"> <li> <p> Avoid unnecessary attribute lookups </p> </li> </ul> <p style="margin-left:30px;"> To put it simply, the variable stores the value. The performance consumption of calling this variable is minimal, while the performance consumption of taking the value of the object's attribute is relatively high. for example: </p> <pre class="brush:php;toolbar:false">var query=window.location.href.subtring(window.location.href.indexOf(“?”));
This code has 6 attribute searches that are particularly inefficient. It is best to change it to:
var url=window.loaction.href;var query=url.substring(url.indexOf(“?”));
This optimization improves the efficiency a lot.
-
optimization loop
1) Decrease iteration: Most loops start from 0 and increase the loop. In many cases, it is more efficient to decrease the loop from the maximum value.
2) Simplify the termination conditions: Since the termination conditions will be judged every time it loops, simplifying the termination conditions can also improve loop efficiency.
3) Simplify the loop body: The loop body is the most executed, so the optimization of the loop body must be ensured.
-
Avoid parsing js code string
When parsing js code strings in js code, a parser must be restarted to parse the code, which causes relatively large performance consumption, so try to avoid functions such as eval and function constructing js code words.
String function, when setTimeout passes a string.
-
The native method is faster, so try to use the native method.
-
Switch statement is faster.
-
Bitwise operators are faster.
2. Code specifications
-
Code comments:
1) Functions and methods: Each function or method should contain comments describing the function, input and output of the function.
2) Complex algorithms: Comments should be added to complex algorithms so that people can understand the logical thinking of the algorithm.
3) Hack: Comments should also be added to the compatibility code.
4) Large blocks of code: Multiple lines of code used to complete a single task should be preceded by a comment describing the task.
-
Decoupling HTML/JavaScript
Html is the structure, and js is the behavioral layer. They inherently need to interact. When we write code, we should try to reduce the correlation between html and js. Some methods will make them too tightly coupled, such as: js in the html page Declaring js code in the script tag, binding onclick events in the html tag, and rewriting the html code in js will cause HTML and js to be too tightly coupled.
Html rendering should be kept separate from js as much as possible. When js is used to insert data, try not to insert tags directly. Generally, you can directly include and hide tags in the page, and then wait until the entire page is rendered, and then use js to display the tag. .
将html和js解耦可以在调试过程中节省时间,更加容易确定错误的来源,也减轻维护难度。
-
解耦css/JavaScript
JavaScript和css也是非常紧密相关的,js经常对页面的样式做动态修改。为了让他们的耦合更松散,可以通过js修改对应的class样式类。
-
解耦应用逻辑/事件处理程序
在实际开发中我们经常在一个事件函数出来将要处理的所有代码都放在这个事件中,例如:
function handleKeyPress(event){ event=EventUtil.getTarget(event); if(event.keyCode===13){var target=EventUtil.getTarget(event);var value=5*parseInt(target.value);if(value>10){ document.getElementById(“error-msg”).style.display=”block”; } } }
这里就是把逻辑处理代码和事件处理代码放到一起,这样会让调试不好调试,维护难度变高,而且要是突然修改要新增加一个事件做同样类似的逻辑处理,那就要复制一份逻辑处理代码到另一个事件函数中。较好的方法是将应用逻辑和事件处理程序分离开。例如:
function validateValue(value){ value=5*parseInt(value); if(value>10){ document.getElementById(“error-msg”).style.display=”block”; } }function handleKeyPress(event){ event=EventUtil.getEvent(event); if(event.keyCode===13){ var target=EventUtil.getTarget(event); validateValue(target.value); } }
这样事件处理和逻辑处理就分离开了,这样做有几个好处,可以让你更容易更改触发特定过程的事件,其次可以在不附加到事件的情况下测试代码,使其更易创建单元测试或是自动化应用流程。
事件和应用逻辑之间的松散耦合的几条原则:
-
勿将event对象传给其他方法;只传来着event对象中所需要的数据;
-
任何可以在应用层面的动作都应该可以在不执行任何时间处理程序的情况下能正常运行。
-
任何时间处理程序都应该处理事件,然后将处理转交给应用逻辑。
-
避免全局变量
这样会让脚本执行一致和可维护,最多创建一个全局变量。类似jQuery一样,所以方法属性都在$对象当中,避免对全局变量造成过多的污染。
-
尽量使用常量
数据和使用它的逻辑进行分离要注意一下几点:
-
重复值
-
用户界面字符串
-
url
-
任意可能会更改的值
-
其他优化
-
多变量声明时用一条语句逗号隔开声明
-
对dom的操作的优化
-
对dom进行html代码插入尽量在最后一次添加到dom对象中。
-
innerHTML的效率要比appendChild的效率高,以为innerHTML会创建一个HTML解析器,然后使用内部的DOM调用来创建DOM结构,而非基于JavaScript的DOM调用,由于内部方法是编译好的而非解释执行,所以执行快的多。
-
使用事件委托减少绑定的事件数量。
-
尽量少用到返回HTMLCollection语句。

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment
