In the past, I turned to an article about the wonderful use of | and & amp; in JavaScript. Below are some optimization methods. The first piece of code emphasizes this usage. I used a switch in my project. Later I found this code ugly, so I wrote it as |, later, when I tested the performance, I found that the performance was an order of magnitude. It can be seen that this method can increase the performance in some cases, but I am not sure what the situation will improve the performance, because I usually test the performance of switches and | & is similar.
Original code:
The Code is as follows:
Switch (this. now_char = this. str. charAt (this. index )){
Case "/":
If (this. handleNote () continue; else this. str2 + = this. now_char;
Break;
Case "\"":
Case "\'":
If (this. handleStr () continue; else this. str2 + = this. now_char;
Break;
Case "\ n ":
If (this. handleLine () continue; else this. str2 + = this. now_char;
Break;
Case "{":
Case "}":
If (this. handleDepth () continue; else this. str2 + = this. now_char;
Break;
Case ":": if (this. handleJson () continue; else this. str2 + = this. now_char; break;
Default:
If (this. handleKeyword () continue; else this. str2 + = this. now_char;
Break;
}
After the code is rewritten, the function is of course the same view sourceprint? 1 (this. now_char = "/" & (this. handleNote () | (this. str2 + = this. now_char) |
(This. now_char = "\" "| this. now_char = "\ '") & (this. handleStr () | (this. str2 + = this. now_char) |
(This. now_char = "\ n" & (this. handleLine () | (this. str2 + = this. now_char) | (this. now_char = "{" | this. now_char = "}") & (this. handleDepth () | (this. str2 + = this. now_char) |
(This. handleKeyword () | (this. str2 + = this. now_char ))
The second method I chew on is more concise. |
The second piece of code utilizes a feature: (ele = document. createElement ("p"); // This expression returns a dom element, and the value is returned to the parentheses.
The following code is displayed:
The Code is as follows:
Var mixin = function (target, options ){
For (var I in options ){
Target [I] = options [I]
}
}
Var ele = null;
Mixin (ele = document. createElement ("p "),{
Id: "aa ",
ClassName: "bb ",
InnerHTML: "sss"
})
Document. body. appendChild (ele)
Debug (ele. id) // aa
Debug (ele. className) // bb
Debug (ele. innerHTML) // sss
This code is because I am bored with a lot of statements when creating a dom element:
The Code is as follows:
Var ele = document. createElement ("p ")
Ele. id = "aa ";
Ele. className = "aa"
Ele. innerHTML = "sss"
Wait.
The above code is displayed.
The above principle can also be used to write code (ele = document. createElement ("p ")). className = "aa"; does it save some space? The above sentence saves a variable name, huh.