New ES features with TypeScript and JS performance optimizations

ES2015

1, Proxy

Proxy objects are used to create a Proxy for an object, enabling interception and customization of basic operations (such as property lookup, assignment, enumeration, function call, etc.)

Note: Can be understood as a gatekeeper, through which to obtain and modify

Use:

const person = {}
cont personProxy = new Proxy(person, {
    get(target, property) {
        return property in target ? target[property] : 'default'
    },
    set(){}})Copy the code

Scenario: THE VUE3 property Proxy uses a Proxy

2. Compare Proxy with defineProperty

Proxy is more powerful than defineProperty, for example:

  • Proxy listens on all objects, while defineProperty listens on specific properties, which needs to be specified
  • DefineProperty cannot listen to attribute additions and deletions while Proxy can
  • DefineProperty cannot listen for array changes
  • Proxy listens in a non-intrusive way, defineProperty does not

3, Reflect

Reflect is a built-in object that provides a way to intercept JavaScript operations. Reflect is not a function object, so it is not constructable.

  • Provides a unified object manipulation Api
  • You can’t pass new. It’s a static method class
  • Has 13 methods (originally 14, eliminated one)
Reflect.apply(target, thisArgument, argumentsList) // We can call a function and pass an array as an argument. Similar to function.prototype.apply ().

Reflect.construct(target, argumentsList[, newTarget]) // New to the constructor is equivalent to new target(... The args).

Reflect.defineProperty(target, propertyKey, attributes) // Similar to object.defineProperty (). Returns true if the setting was successful

Reflect.deleteProperty(target, propertyKey) // As the delete operator of the function, equivalent to executing delete target[name].

Reflect.get(target, propertyKey[, receiver]) // Get the value of a property on the object, similar to target[name].

Reflect.getOwnPropertyDescriptor(target, propertyKey) / / is similar to the Object. GetOwnPropertyDescriptor (). Return the corresponding attribute descriptor if the attribute exists in the object, and undefined otherwise.

Reflect.getPrototypeOf(target) // Similar to object.getPrototypeof ().

Reflect.has(target, propertyKey) // Determine whether an object has a property, which is exactly the same as the in operator.

Reflect.isExtensible(target) // Similar to object.isextensible ().

Reflect.ownKeys(target) // Return an array containing all of its properties (excluding inherited properties). (Similar to object.keys () but not affected by Enumerable).

Reflect.preventExtensions(target) // similar to object.preventExtensions (). Returns a Boolean.

Reflect.set(target, propertyKey, value[, receiver]) // A function that assigns values to attributes. Returns a Boolean or true if the update was successful.

Reflect.setPrototypeOf(target, prototype) // The function that sets the object prototype. Returns a Boolean or true if the update was successful.
Copy the code

4, Symbol

  • Symbol is a new primitive data type
  • The main function is to add a unique identifier (think of as a key) to the object.
  • Use Symbol simulation to implement object private members to avoid and resolve conflicts
  • Data types: Number, string, function, bigInt, symbol, Boolean, undefined, object
  • Special types: NULL,JS has a long-standing Bug. In the original version of JS, the 32-bit system was used. For performance purposes, the type information of variables was stored in low order. The beginning of 000 represents an object, while null represents all zeros, so it was wrongly identified as object

5, the class extends

  • Where inheritance was previously implemented as a prototype, it can now be implemented as a function internally via the extend of class

  • Since class is essentially a function, it will have a Prototype property. When a new class is created, it will assign the porotoType property of the class to the proto property of the new object

  • Prototype is a property of the function, which is a pointer. For constructors, prototype is a property of the constructor. Prototype can also be an object. Prototype is the prototype object of an instance of an object. So prototype is both a property and an object. When new an object, it can be understood that the object has no ptotoType property, so give the ptotoType to an object’s proto

6. Iterator pattern

  • Provides a uniform, iterable interface
  • This pattern is implemented at the grammatical level

7. Generator

  • A method preceded by an asterisk (*) represents a generator function
  • Successful execution returns an object
  • You need to continue with the next method
  • Pause internally via yield
  • Next, the value after yield is returned as the result of the next
  • It also returns a done state
  • Application scenario: Sender

8 es2016.

  • The includes method: check whether the directory exists and is compatible with NaN
  • Exponent operator: **, such as 2 ** 10

9 es2017.

  • Object. The method of values
  • The object.entry method retrieves the contents of the object as an array of keys and valye
  • PadStart,padEnd, for example, add a 0 before a number


Typescript

An overview of the

  • Ts is a programming language based on JS, which solves the shortcomings of JS type system.
  • With TS, you can improve the reliability of your code
  • Ts is a superset of JS
  • Js is dynamically typed and TS is statically typed
  • Ts adds a lot of features based on JS

Ts scope problem

  • Variables are in global scope by default and are not allowed to duplicate
  • By default, use export {} to become a module export

Ts type

  • Type Object: function, array, Object
  • Array type: Array, number[]
  • Tuple types: tuple types, which can be understood as data types with specific types and specific lengths
  • Enumeration type: enum, the number is automatically increments, the string must be given a value, eventually will become a two-way key-value pair
  • Function type:
Function declaration1, parameter type restrictions2The return value type function expression is indicated by the arrow functionCopy the code
  • Any type: Accepts any type: any, which is a dynamic type
  • Implicit type inference: If a type is not declared, automatic type inference takes place
  • Type assertion: When inferring cannot be done, as keyword, Angle bracket, Angle bracket and JSX conflict, as is recommended

interface

  • A convention, a specification
  • Interface Defines an interface
  • The format is: key: type
  • Agree on the structure of the object and must implement the content defined by the interface
  • Optional members: Add greetings
  • Read-only member: adds readonly, and cannot be changed after assignment
  • Any member: [x: types]: types

class

  • Class is used to describe the abstract characteristics of a specific class of transactions
  • Class access modifiers: private, public (default), proteted (protected)
  • Proteted: Only allowed in subclasses
  • Private: Only internal use of the class is allowed
  • Read-only attribute: readonly, which must be followed by a modifier
  • It is best to limit an interface to only one capability. A class can implement more than one interface, using the implements keyword, and separate multiple interfaces using commas




Performance optimization

  • Memory management
  • Garbage collection and common GC algorithms
  • V8 engine garbage collection
  • The performance tools

Memory management

  • Memory: composed of read and write units, representing an operational space
  • Management: to manipulate the application, use and release of a space artificially
  • Memory management: Developers actively apply for space, use space, and release space
  • Js has no API to directly open up space, but use variable declaration, create functions, create classes and other ways to open up space through the browser
  • When using the space, pay attention to avoid space leakage caused by improper operations

The garbage collection

  • Js memory management is automatic
  • An object is garbage when it is no longer referenced
  • Objects that cannot be accessed from the root are garbage

To object

  • Objects that are accessible are reachable objects
  • The criterion of reachability is whether it can be found from the root (from the root, to the scope chain lookup, etc.)
  • Root: can be thought of as a global variable object

Introduction to GC Algorithm

  • GC: Short for garbage collection mechanism
  • GC can find garbage in memory and free and reclaim space
  • What is the garbage in the GC?
  • An object that is no longer needed in the program
  • An object that is no longer accessible in the program
  • GC is a mechanism, garbage collector to complete the specific work, and the work is to find garbage and free and reclaim space; Algorithms are the rules that work to find and recycle
  • Commonly used algorithms: reference counting, tag clearing, tag sorting, generational collection

GC: reference count

  • Core idea: Set the number of references, determine whether the current number of references is 0, when 0, recycling
  • Implementation principle:
  • Maintain a reference counter, incrementing the counter by 1 when there is a variable reference, subtracting the counter by 1 when there is no reference. When the counter is zero, GC reclaims, freeing up space
  • Reference counters: Because counters exist, they are different from other mechanisms

The advantages and disadvantages

  • When the value is found to be 0, it is reclaimed immediately
  • Reduce program lag time
  • Memory is not slow because it is constantly monitored and reclaimed when it is almost full
  • However, due to the need to maintain the counter changes, the time overhead is greater than other mechanisms
  • Also, if two objects refer to each other, they cannot be deleted because they are not zero

Mark clear

  • Core idea: divided into two stages, the first stage will mark the active object, the second mark will be unmarked to remove, at the same time eliminate the previous mark
  • If the object can be found from the root and along the scope chain, it is reachable; otherwise, it is unreachable and will be cleared by GC

The advantages and disadvantages

  • Can solve the cross-reference problem that cannot be solved when reference counting
  • When referencing each other, the recursive lookup from the root becomes unreachable after scoping and is therefore cleared
  • Disadvantage 1: The space address is discontinuous after the clearance, resulting in space waste
  • Disadvantage 2: Fragmentation, not immediately cleared

Tag to sort out

The difference between the marking stage and the marking clearing mechanism is that after the first stage is completed, before the second stage of marking clearing, a spatial arrangement is carried out to move the location of the object so that the reachable space addresses of the active object are continuous, and then the clearing operation is carried out

  • Reduce fragmentation

  • Garbage objects are not immediately collected

V8

  • V8 is a major JS execution engine already in use on the Chrome platform

  • V8 uses just-in-time compilation

  • Memory limit

    64 indicates 1.5g in the system

    32 indicates 800 meters in the system

    The reason is that it takes 500 milliseconds to use the delta flag when 1.5 gb of memory is used. Using other methods takes 1 second, and from the user experience point of view, it is reasonable to set this online and use the increment flag

V8 garbage collection policy

  • The idea of generational recycling is adopted, which is divided into the new generation and the old generation, and different algorithms are adopted for different objects

  • First division, according to the new generation, the old generation of generational recycling model

  • Next, spatial replication

  • Mark clear

  • Tag to sort out

  • Mark the incremental

Cenozoic recovery
  • Cenozoic space is divided into two equal parts

  • In a 64-bit system, it is a 32M single

  • In 32-bit systems it is a 16M single

  • Cenozoic refers to objects that live for a short time

The recycling process adopts the copy algorithm + mark arrangement

  • The two equally divided Spaces are divided into: the use space is From, and the space space is To
  • If a variable is declared, open space will be stored in the From space, as an active object, at this time To space is idle state, unused
  • When the From space is used TO a certain percentage, THE GC operation starts, in the order of tag collation and then copy the live object TO the TO space. The “From” field is released after copying, and the “TO” is programmed TO use the status. It’s swapped

Recycling details: Copies of the From To To space are promoted (promotion is moving the new generation objects into the old generation space). The criteria for promotion are:

  • 1. The new generation that survived a round of GC needs promotion.
  • 2, TO space usage exceeds 25%, copy all TO the old generation (because From and TO need TO exchange, ensure enough space)
Old age recovery
  • Old generation objects are stored in the old generation area
  • The old generation space size is limited to 1.4g for 64-bit operating systems and 700M for 32-bit operating systems
  • An old generation object is an object that has a long lifetime
  • The old generation recycling mainly adopts the algorithm of mark clearing, mark sorting and incremental mark
  • First: the use of tag cleaning to complete garbage recycling, faster
  • Label arrangement needs to be triggered according to conditions: when the new generation space is promoted to the old generation space, but the space cannot be satisfied, comparative arrangement will be carried out for spatial optimization first.
  • Finally, the efficiency is optimized by using incremental marker

And the details of the new generation

  • The new generation trades space for time
  • Old generation is not suitable for replication algorithm, the reason: large, long time

Mark increment: the garbage collection and program execution split alternate execution, short time, weak user perception, good experience

V8 Execution Process

  • Scanner – scanner that scans plain text code. Do the lexical analysis, get the lexical unit, the smallest unit
  • Parser – A parser that converts the lexical data into an AST tree
  • Preparser. Preparser. Full

Preparsing benefits: Unused code is skipped, no AST is generated, variable referenced and declared scopes are created, specific errors are thrown according to specifications, and resolution is faster

Full parsing: Parsing the code being used, generating the AST, building specific scopes, variable references, declarations, etc., throwing any syntax errors

The sample

// It is not called when declared, so it is considered not to be executed, and preparse is run
function foo() {
    console.log('foo')}// When the declaration is not called, so it will be considered not to be performed in the dia, for pre-parsing
function fn() {}

// The function is executed immediately, with only one full parse
(function bar() {
    
})()

// To execute foo, foo must be fully parsed again. Foo is parsed twice
foo()
Copy the code
  • Lgnition is an interpreter provided by V8

To convert the AST into bytecode

  • TurBoFan is a compiler module

Before converting data to machine code (assembly code)

Function shake and throttling