Location>code7788 >text

Difference between structuredClone and () cloning in JavaScript

Popularity:966 ℃/2024-09-06 10:49:26

Similarities and differences between structuredClone and (()) clones in JavaScript

I. What is structuredClone?

1. Development of structuredClone

structuredClone Yes, it is.ECMAScript introduced in the 2021 (ES12) standard.ECMAScript 2021 Specification officially published in June 2021

Starting in March 2022, this feature is available on the latest devices and browser versions

Baseline 2022 Newly available
Since March 2022, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

2. structuredClone functions

2.1 Functions

globalstructuredClone() method makes a deep copy of the given value using a structured cloning algorithm

2.2. syntax

structuredClone(value)
structuredClone(value, { transfer })

2.2 Parameters

  • value: the object being cloned
  • transfer: a transferable array

2.3 Return values

The return value is a deep copy of the original value

2.4.

If any part of the input value is not serializable, throw theDataCloneError exceptions

3. Usage

3.1 General usage

const obj = {
  name: 'sunrise',
  sex: 'male',
  blog: {
      csdn: '/?type=blog',
      jj: '/user/2409752520033768/posts'
  },
  games: ['cf', 'Dark Horses.', 'cs'],
  age: 18,
  bool: true,
  set: new Set([1,2,3]),
  map: new Map([['a', 'b'], ['c', 'd']]),
  null: null,
  und: undefined
}
const cloneObj = structuredClone(obj);

image

3.2. transfer usage

transfer is an array of transferable objects, the values in which are not cloned, but are transferred to the copied object

const buffer = new ArrayBuffer(16);
('buffer', buffer);
const cloned = structuredClone(buffer, { transfer: [buffer] });
('buffer', buffer);
('cloned', cloned);

image

Difference between structuredClone and (())

1. Supported data types

As you can see from the example above, thestructuredClone Many medium data types are supported, both basic types and common objects.

1.1. structuredClone

1.1.1 Types of support
  • basic type
  • common object
  • Date boyfriend
  • RegExp boyfriend
  • Map
  • Set
  • ArrayBuffer
  • TypedArrays
  • Blob
  • File
  • ImageData
  • MessagePort
  • null、undefined
  • NaN、Infinity、-Infinity
  • circular reference
1.1.2 Types not supported
  • function (math.)
  • symbol
  • WeakMap
  • WeakSet
  • HTMLElement
1.1.3 Examples
const port1 = new MessageChannel().port1
const obj = {
  date: new Date(),
  regex: /test/i,
  map: new Map([['key1', 'value1'], ['key2', 'value2']]),
  set: new Set([1, 2, 3]),
  arrayBuffer: new ArrayBuffer(8),
  typedArray: new Uint8Array([1, 2, 3]),
  blob: new Blob(['Hello, world!'], { type: 'text/plain' }),
  file: new File(['file content'], '', { type: 'text/plain' }),
  imageData: (() => {
    const canvas = ('canvas');
    const context = ('2d');
    return (100, 100);
  })(),
  messagePort: port1,
  nullValue: null,
  undefinedValue: undefined,
  nanValue: NaN,
  infinityValue: Infinity,
  negativeInfinityValue: -Infinity,
  circularRef: {}
};

// Creating Circular References
 = obj;

// clone (loanword) obj boyfriend
const clonedObj = structuredClone(obj, {transfer: [port1]});

// output to validate the
(clonedObj);

image

const obj = {
  func: function() { return "I'm a function"; }, // function (math.)
  symbol: Symbol('uniqueSymbol'), // Symbol
  weakMap: new WeakMap(), // WeakMap
  weakSet: new WeakSet(), // WeakSet
  element: ('div') // HTMLElement
};

// Trying to clone an object
try {
  const clonedObj = structuredClone(obj);
  (clonedObj); // This line won't run if an error is thrown
} catch (error) {
  ('Error:', error); // DataCloneError: Failed to execute 'structuredClone'
}

image

1.2. (())

1.2.1 Types of support
  • digital (electronics etc)
  • string (computer science)
  • boolean
  • arrays
  • common object
1.2.2 Types not supported
  • Date, Map, Set, RegExp, Function, undefined, symbol, Infinity, NaN,circulate Quote...

For more information you can read the following article

What you need to know()

1.2.3 Examples
(({
  a: null,
  b: undefined,
  c: NaN,
  d: Infinity,
  e: () => ({}),
  f: new Map(),
  
  h: Symbol('a'),
  i: Infinity
}))

// Return the value

{
  "a": null,
  
  "c": null, "d": null, "d": null, "f": {}, {}
  "f": {},
  "g": {},
  "i": null
}

image

2. Circular references

2.1. structuredClone

Can correctly handle circular references in objects

2.2. ()

If there are circular references in the object, the call throws an error and the clone fails.

image

3. Performance

3.1. structuredClone

Typically performs better with complex objects, especially when containing large amounts of data of non-JSON compatible types, as it is a native method designed for deep cloning and is internally optimized for many complex scenarios

3.2. ()

May perform well with simple, JSON-compatible data structures, but is inefficient with complex objects or non-JSON compatible types.

4. Browser compatibility

4.1. structuredClone

It is a newerAPIThe following is not supported in some older browsers

image

image

4.2. ()

Wide support in both modern and older browsers

image

III. Summary

  • structuredClone Provides broader data type support and the ability to handle circular references for complex scenarios
  • () Ideal for handling simplicity,JSON Compatible data structure, but has limitations when dealing with complex data types or circular references
  • Both have limitations, you need to pay attention to the data type of the cloned object before making a choice when cloning.

consultation

  • structuredClone
  • What you need to know()