Front-end internship record - code specification & coding convention & performance optimization

Reason for writing this article        

This article is to record some code specification problems encountered in the project after entering the company, the specifications taught by the leader and some code specifications that I learned in private. Code specifications are really important! !

Three days after entering the company, I started to contact the project. The project is agile development. The task of our department is to iterate the project to the next stable version. This is where the nightmare started. After I started to iterate the version, I finally understood why those experienced programmers value code specifications very much. Because they don’t pay attention to code specifications, it really takes a lot of time to understand what others wrote! ! !

Most of this project has no comments , common class names (such as "main", "container"), inconsistent indentation , strange variable names and method names (all method names such as "OK") Wait, there are still many questions. Next, I will share some code specifications I have learned so far, hoping to help everyone.

1. Sass & BEM naming convention

Sass official website: Poke me to go

Sass (also called scss) is very easy to use. It is much more convenient to write than css. After that, most of the work should be done with sass. Getting started is also very simple. I used sass for company projects, so I spent two days to After studying the official website, you can understand everything used in the basic projects.

BEM: B (Block), E (Element), M (Modifier), is a front-end CSS naming method proposed by the Yandex team. Generally, it is named like this: B__E-M, directly on the example:

For example, I have an html structure like this: the first div I wrote is Test. In the company, we usually write or write the file name of this file according to the specific function.

    <div class="Test">
        <div class="Test__fiflter">
            <div class="Test__fiflter-content">
            </div>
        </div>
        <div class="Test__searchResult"></div>
    </div>

Then you can combine Sass to write styles:

    <style scoped lang="scss">
        .Test{
            /* todo */
            &__fiflter{
                /* todo */
                &-content{
                    /* todo */
                }
            }
            &__searchResult{
                /* todo */
            }
        }
    </style>

This is just the most basic function, the purpose is to make the structure clearer and more convenient when writing styles, but BEM can not be named at any time. It should be used when the structure has a clear structural cascading relationship, and it depends on the situation at other times.

"&" is the most basic function of sass. Sass plays a big role in the project, such as defining global style variables. I have never understood why it is so complicated to write a style in order to define it as a global, such as setting a color " "white" is written as "primary-color". Later, the leader told me that it is for the convenience of maintenance when iterating later. It is also from this time that I have the awareness of writing standardized code and maintainable code !

Sass has a lot of functions. I suggest everyone go to the official website to learn it twice. If you want to use it later, even if you forget to take a look at the official website, it will be very fast!

2. Some basic JS code specifications

Explanation: Most of them are learned from W3C official website and ruby ​​book .

1) Variable names and function names are written in camel case;        

2) Use nouns for variable names;       

3) The function name starts with a verb; such as: getName(), isDisabled()

4) The constant value is capitalized and connected with an underscore;

5) Leave spaces around operators;       

6) Use 4 spaces for code indentation, do not use tabs;

7) Comments should be written in the following places: functions and methods, large code blocks, complex algorithms;

8) Variable type transparency; such as let flag = false // boolean value let name = "" // string

3. Coding conventions

1) Do not declare global variables

  • On the one hand, global variables and global functions may be overwritten, so it is not safe.
  • On the other hand, it is related to the garbage collection mechanism of JS . Global variables are variables under the window. As long as the window itself is not killed, the global variables will not disappear, so a "memory leak" is caused, such as the one in one of your variables. You only want to use the value once, and if you declare it as a global value, it will always exist and occupy memory. The garbage collection mechanism will not regularly recycle global variables, but only recycle local variables.
  • Another point is mentioned in "Avoiding global lookups" in performance.

So please use local variables instead of global variables .

2) Use const, let instead of var

In the project, I often see that the code written by the predecessors basically uses let and const, and rarely uses var.

We all know their differences. For example, let and const have block-level scope, and var has function scope. However, I only knew "this sentence" before, and I didn't understand what it was useful for. Now let me tell you.

  • There is also a part of the reason for the garbage collection mechanism, because const and let are related to block-level scope, the garbage collection mechanism can find the variables declared by these two keywords earlier and recycle them (because in most cases the block-level scope terminates earlier than the function scope).
  • Use const first, let second. I don’t know if you know about static code analysis. Using const is beneficial to static code analysis tools to help us analyze code. When we know that a value will be changed in the future, we use let, which is very helpful for later code inspection.

These coding conventions help to improve performance, especially the habit of using var must be changed.

3) Don't new object()

Picture from W3C official website

reason:

  •  new Object() is essentially a method call, so you need to find those Arrays, RegExps, etc. on the prototype chain of the Object. After finding them, you need the stack to save them, and release the stack after the method call ends. So time consuming.
  • New String, Number, and Boolean return their corresponding instances, which can be understood by looking at the types printed below:
            let obj = new Number('25')
            console.log(typeof(obj)) // object
            let obj1 = Number('25')
            console.log(typeof(obj1)) // number
    
            let str = new String('123') 
            console.log(typeof(str)) // object
            let str1 = String('123')
            console.log(typeof(str1)) // string
    
            let bool = new String(true)
            console.log(typeof(bool)) // object
            let bool1 = Boolean(true)
            console.log(typeof(bool1)) // boolean
  • There is another aspect of "statement minimization", which will be mentioned in the performance below.

4) Do not use eval() and with()

  • The eval() function is used to run text as code, it is definitely not safe, don't use it!
  • I personally feel that the with function is useless. It mainly makes it easier to use a certain variable, but using local variables can also achieve the same effect. The with statement will create its own scope, which will lengthen the scope chain in the code, so it is best not to use it!

The most important coding conventions are so much for the time being, and new ones will be updated in time in the future.

5) Do not assign continuously

For example let a = b = c = 1;

This line of code does assign 1 to a, b, and c, but b and c will be declared as global variables.

4. Performance optimization

1) Simplify the loop statement

This optimization is not only applicable to JS, any language can speed up by doing this. I also saw it when I saw the big guys doing optimization when they brushed the power button. In a for loop, every time the loop is executed, each statement in the loop is executed .

for(let i = 0; i < arr.length; i++); 

This for loop statement will get the length of arr every time, so it does repeated things, so it should be modified:

let i;

let len = arr.length;

for( i = 0; i < len; i++);

This only requires one visit. In fact, any value like this that needs to be used more than twice should be stored in a separate variable, which will speed up the execution.

2) Statements are minimized

Every line of JS code needs to be parsed by the JS engine, and achieving the goal with the least amount of code is what developers want.

The following two examples: When declaring arrays and objects, one line of code replaces the above four lines of code.

// bad  new object
let arr = new Array(3)
arr[0] = 1
arr[1] = 2
arr[2] = 3

// good 字面量方式
let arr = [1, 2, 3]
// bad
let student = new Object();
student.name = "xx";
student.age = 11;
student.sayHello = function(){ console.log("Hello") };

// good
let student = {
    name:"xx",
    age:11,
    sayHello:function(){
        console.log("Hello")
    }
};

Declare variables:

// bad
let name = "xxx";
let name1 = "zzz";
let name2 = "ccc";

// good
let name  = "xxx", 
    name1 = "zzz",
    name2 = "ccc"; 

3) Scope awareness — avoid global lookups

Thanks Ruby Books! I have never thought about this problem. Using global variables and global functions is definitely slower than local, because accessing global variables requires a layer-by-layer search for scope, and the global scope will always be found.

Give an example of vue:

When you define a state as name in vuex, if you want to get this state in the component, you should directly get it like this:

this.$store.state.name, every time you use a point, you have to search for the corresponding scope. If you also use the module, it will be more troublesome to write. If you add the module name as test, then the value in the component should be like this Pick:

this.$store.test.state.name, which is even more troublesome.

Think about writing such a long list every time a value is taken, which is not only difficult to write but also consumes performance . So vuex provides a solution for us to take the value like this:

Use mapState, so to get this value in vuex later, just use "name" directly.

computed:{
    ...mapState({
        name: (state) => state.test.name
    })
}

In JS, it is enough to use local variables to save, so you need to take the global search scope once. So after learning JS, it is really much easier to understand the underlying principles of Vue.

If there is something wrong, I hope you guys can correct me a lot!

Guess you like

Origin blog.csdn.net/huiaixing/article/details/125855613