Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the skills of JS programming optimization

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

The main content of this article is to explain "what are the optimization skills of JS?", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what are the skills of JS programming optimization"?

1. Write code in a strongly typed style

JS is weakly typed, but you can't write code too casually, which reflects a poor coding style. The following points are explained:

(1) when defining a variable, specify the type, tell the JS interpreter what data type the variable is, and don't let the interpreter guess, such as bad writing:

Var num, str, obj

Three variables are declared, but it doesn't really work, because the interpreter doesn't know what type they are, and a good way to write them would look like this:

Var num = 0, str ='', obj = null

When defining variables, give him a default value, which is not only convenient for the interpreter, but also for the person who reads the code, and he will know what these variables might be used for.

(2) do not change the type of variable at will, such as the following code:

Var num = 5; num = "-" + num

On line 1 it is an integer, and on line 2 it becomes a string. Because JS will eventually be interpreted as an assembly language, the type of assembly language variables must be determined, and if you change an integer into a string, the interpreter has to do some extra processing. And this coding style is not advocated, there is a variable line 1 is an integer, line 10 becomes a string, line 20 becomes an object, which makes people who read the code more confused, it is obviously an integer, how suddenly become a string. A good way to write it would be to define another variable in a string:

Var num = 5; var sign = "-" + num

(3) the return type of the function should be determined, for example, the following uncertain words:

Function getPrice (count) {if (count)

< 0) return ""; else return count * 100; } getPrice 这个函数有可能返回一个整数,也有可能返回一个空的字符串。这样写也不太好,虽然它是符合 JS 语法的,但这种编码风格是不好的。使用你这个函数的人会有点无所适从,不敢直接进行加减乘除,因为如果返回字符串进行运算的话值就是 NaN 了。函数的返回类型应该是要确定的,如下面是返回整型: function getPrice(count){ if(count < 0) return -1; else return count * 100; } 然后告诉使用者,如果返回-1 就表示不合法。如果类型确定,解释器也不用去做一些额外的工作,可以加快运行速度。 2. 减少作用域查找 (1)不要让代码暴露在全局作用域下 例如以下运行在全局作用域的代码: var map = document.querySelector("#my-map"); map.style.height = "600px"; 有时候你需要在页面直接写一个 script,要注意在一个 script 标签里面,代码的上下文都是全局作用域的,由于全局作用域比较复杂,查找比较慢。例如上面的 map 变量,第二行在使用的时候,需要在全局作用域查找一下这个变量,假设 map 是在一个循环里面使用,那可能就会有效率问题了。所以应该要把它搞成一个局部的作用域: !function(){ var map = document.querySelector("#my-map"); map.style.height = "600px"; }() 上面用了一个 function 制造一个局部作用域,也可以用 ES6 的块级作用域。由于 map 这个变量直接在当前的局部作用域命中了,所以就不用再往上一级的作用域(这里是全局作用域)查找了,而局部作用域的查找是很快的。同时直接在全局作用域定义变量,会污染 window 对象。 (2)不要滥用闭包 闭包的作用在于可以让子级作用域使用它父级作用域的变量,同时这些变量在不同的闭包是不可见的。这样就导致了在查找某个变量的时候,如果当前作用域找不到,就得往它的父级作用域查找,一级一级地往上直到找到了,或者到了全局作用域还没找到。因此如果闭包嵌套得越深,那么变量查找的时间就越长。如下: function getResult(count){ count++; function process(){ var factor = 2; return count * factor - 5; } return process(); } 上面的代码定义了一个 process 函数,在这个函数里面 count 变量的查找时间要高于局部的 factor 变量。其实这里不太适合用闭包,可以直接把 count 传给 process: function getResult(count){ count++; function process(count){ var factor = 2; return count * factor - 5; } return process(count); } 这样 count 的查找时间就和 factor 一样,都是在当前作用域直接命中。这个就启示我们如果某个全局变量需要频繁地被使用的时候,可以用一个局部变量缓存一下,如下: var url = ""; if_(window.location.protocal === "https:"){ url = "wss://xxx.com" + _window.location.pathname + _window.location.search; } 频繁地使用了 _window.location 对象,所以可以先把它缓存一下: var url = ""; var location = _window.location; if(location.protocal === "https:"){ url = "wss://xxx.com" + location.pathname + location.search; } 搞成了一个局变变量,这样查找就会明显快于全局的查找,代码也可以写少一点。 3.避免==的使用 这里你可能会有疑问了,有些人喜欢用==,有些人喜欢用===,大家的风格不一样,你为什么要强制别人用===呢?习惯用==的人,不能仅仅是因为==比===少敲了一次键盘。为什么不提倡用==呢? (1)如果你确定了变量的类型,那么就没必要使用==了,如下: if(typeof num != "undefined"){ } var num = parseInt(value); if(num == 10){ } 上面的两个例子都是确定类型的,一个是字符串,一个是整数。就没必要使用==了,直接用===就可以了。 (2)如果类型不确定,那么应该手动做一下类型转换,而不是让别人或者以后的你去猜这里面有类型转换,如下: var totalPage = "5"; if(parseInt(totalPage) === 1){ } (3)使用==在 JSLint 检查的时候是不通过的: if(a == b){ } 如下 JSLint 的输出: Expected ‘===’ and instead saw ‘==’. if(a == b){ (4)并且使用==可能会出现一些奇怪的现象,这些奇怪的现象可能会给代码埋入隐患: null == undefined //true '' == '0' //false 0 == '' //true 0 == '0' //true ' ' == 0 //true new String("abc") == "abc" //true new Boolean(true) == true //true true == 1 //true 上面的比较在用===的时候都是 false,这样才是比较合理的。例如第一点 null 居然会等于 undefined,就特别地奇怪,因为 null 和 undefined 是两个毫无关系的值,null 应该是作为初始化空值使用,而 undefined 是用于检验某个变量是否未定义。这和第 1 点介绍强类型的思想是相通的。 4. 合并表达式 如果用 1 句代码就可以实现 5 句代码的功能,那往往 1 句代码的执行效率会比较高,并且可读性可能会更好 (1)用三目运算符取代简单的 if-else 如上面的 getPrice 函数: function getPrice(count){ if(count < 0) return -1; else return count * 100; } 可以改成: function getPrice(count){ return count < 0 ? return -1 : count * 100; } 这个比写一个 if-else 看起来清爽多了。当然,如果你写了 if-else,压缩工具也会帮你把它改三目运算符的形式: function getPrice(e){return 0>

EBay Mutual 1PUR 100mm}

(2) Company, etc.

The expression uses the assignment operation to return the assigned value, and the order of execution is from right to left, as follows:

Overtime = favhouse = listingDetail = {...}

Sometimes you see people write like this:

Var age = 0; if ((age = + form.age.value) > = 18) {console.log ("you are an adult");} else {consoe.log ("kids, you still have" + (18-age) + "coming of age");}

Also use the assignment expression to return a value, assign a value in if while judging by its return value, and then there is already a value in else. The + sign above converts the string to an integer.

(3) self-increasing

Using self-increment can also simplify the code. As follows, every time a message is sent, localMsgId increments by 1:

ChatService.sendMessage (localMsgId++, msgContent)

5. Reduce the number of demons

For example, on line 800 of a file, a sentence pops up:

DialogHandler.showQuestionNaire ("seller", "sell", 5, true)

It will be very confusing, what do the above four constants represent? if I don't check the variable description of that function, I can't quickly realize the use of these constants. These unknown constants are called "magic numbers". So it's best to give these constants a name, especially in some of the more critical places. For example, the above code can be changed to:

Var naireType = "seller", dialogType = "sell", questionsCount = 5, reloadWindow = true; naireHandler.showNaire (naireType, dialogType, questionsCount, reloadWindow)

So the meaning is obvious.

6. Use ES6 to simplify code

ES6 has been developed for many years, and its compatibility is already very good. When used properly, you can make your code more concise and elegant.

(1) replace small functions with arrowhead functions

There are many scenarios where small functions are used. If you write a function, you have to write at least 3 lines of code, but you can do it with one line of the arrow function, such as sorting the array from big to small:

Var nums = [4,8,1,9,0]; nums.sort (function (a, b) {return b-a;}); / / output [9, 8, 4, 1, 0]

If you use the arrow function, the sort is done in one line:

Var nums = [4,8,1,9,0]; ``nums.sort (a, b = > b-a)

The code looks much simpler, and it is often encountered in setTimeout that you only need to execute one line of code. It is always troublesome to write a function, but it is not very good to use a string, so it is also convenient to use the arrow function in this case:

SetTimeout (() = > console.log ("hi"), 3000)

Arrow functions are called Lambda expressions in other languages such as C++/Java. Ruby has had this grammatical form for a long time, and later C++/Java also implemented this syntax. Of course, the arrow function or Lambda expression is not only suitable for this kind of one-line code, but also for multiple lines of code, but its advantages are more obvious on one line.

(2) class using ES6

Although ES6's class and prototype using function are essentially the same, both use prototypes. But using class can reduce the amount of code and at the same time make the code look more elegant, so much to write with function:

Function Person (name, age) {this.name = name; this.age = age;} Person.prototype.addAge = function () {this.age++;}; Person.prototype.setName = function (name) {this.name = name;}

Using class code to see Cartier is simple and easy to understand:

Class Person {constructor (name, age) {this.name = name; this.age = age;} addAge () {this.age++;} setName (name) {this.name = name;}}

And class can also easily implement inherited and static member functions, so you don't need to go through some skills to achieve it.

(3) string concatenation

You used to use the + sign to concatenate:

Var tpl ='+'1' +'

Now all you have to do is use two backquotes:

Var tpl = `1`

In addition, backquotation marks also support placeholder substitution, which you originally need:

Var page= 5, type= encodeURIComponet ("# js"); var url = "/ list?page=" + page + "& type=" + type

Now all you need is:

Var url = `/ list?page=$ {page} & type=$ {type}`

You don't have to use the + sign to break up the string.

(4) Block-level scope variables

Block-level scope variables are also a feature of ES6. The following code is a model abstraction of a task queue:

Var tasks = []; for (var I = 0; I < 4; iTunes +) {tasks.push (function () {console.log ("I is" + I);} for (var j = 0; j < tasks.length; jacks +) {tasks [j] ();}

But the execution output of the above code is 4Power4, and it is not intended to be outputted, so each task cannot get its index, because the closures are all using the same I variable, and I has become 4, so the execution of closures is 4. What are we going to do? It can be solved as follows:

Var tasks = []; for (var I = 0; I < 4; iTunes +) {! function (k) {tasks.push (function () {console.log ("I is" + k);} (I);} for (var j = 0; j < tasks.length; jacks +) {tasks [j] ();}

I is assigned to k, because k is a parameter of a function, every time the function is executed, the new k must be instantiated, so each time k is a different variable, so the output is normal. But the code looks a little awkward. If you use ES6, just change var to let:

Var tasks = []; for (let I = 0; I

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 210

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report