In JavaScript, the delete operator is used to delete an attribute of an object. For example,

const person = {
    name: 'sudada'.gender: 'female'
}

delete person.name

console.log(person.name) // undefined
Copy the code

Contrary to the most intuitive semantics, using the delete operator does not free memory directly, but invalidates the hidden class in the V8 (Javascript) engine, turning the object into a generic slow object. This leads to a noticeable slowdown in execution speed.

Hidden Class: Since JavaScript is a dynamic programming language, attributes can be added and removed dynamically, meaning that an object’s attributes are mutable, most JavaScript engines (V8) introduced the concept of hidden classes to keep track of the types of objects and variables. At runtime V8 creates hidden classes that are attached to each object to keep track of its shape/layout. This optimizes the property access time.

Reference:

Debuggable.com/posts/under…

Stackoverflow.com/questions/4…

So how do we delete an object’s attributes without using DELETE?

The most efficient way to do this is to set an unwanted property to undefined, for example

const person = {
    name: 'sudada'.gender: 'female'
}

person.name = undefined // Delete the name attribute
Copy the code

Or you can consider using the Spread Operator for objects, for example

const person = {
    name: 'sudada'.gender: 'female'
}
const omit = (prop, { [prop]: _, ... rest }) = > rest;
const newObj = omit('name', person); // Delete the name attribute
Copy the code

For Spread Operator for Objects reference: juejin.cn/post/1

So how to choose delete, undefined and omit?

The figure shows the efficiency (number of executions per second) of the three methods for different Javascript kernels. One obvious conclusion is to set undefined > DELETE > omit.

Instance address: jsperf.com/removing-va…

But if you set it to undefined, you get zero

{
    name: undefined.gender: 'female'
}
Copy the code

Sometimes additional operations are required, for example

JSON.parse(JSON.stringify(person))
/ / or
Object.keys(person).reduce((pre, cur) = > {
    const value = person[cur]
    return value === undefined? pre : {... pre, [cur]: value} }, {})Copy the code

In this way, the efficiency is greatly reduced. Therefore, Map can be used to replace Object in actual services, for example

let map = new Map([['a'.1]])
let obj = { a: 1 };
/ / execution
delete obj.a;
map.delete('a');
Copy the code

From the figure, it is clear that map.delete is better than delete.