<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>
var params = { b:"hello", c: true, d:7 };
var other = Object.assign(params);
var params = { b:"hello", c: true, d:7 };
var other = JSON.parse(JSON.stringify({ b:"hello", c: true, d:7 }));
var params = { b:"hello", c: true, d:7 };
var other = $.extend(true, params);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.assign | |
JSON | |
jQuery.extend |
Test name | Executions per second |
---|---|
Object.assign | 0.0 Ops/sec |
JSON | 435128.7 Ops/sec |
jQuery.extend | 977375.1 Ops/sec |
Benchmark Explanation
The provided benchmark measures the performance of three functions: Object.assign
, JSON.parse(JSON.stringify)
, and $.extend(true, obj)
(in this case, $
refers to jQuery). These functions are used for object assignment or merging, which is a common operation in JavaScript.
Options Compared
The benchmark compares the performance of these three functions:
Object.assign()
: This function takes an object and one or more additional objects as arguments, and returns a new object containing all key-value pairs from the original object and the provided objects.JSON.parse(JSON.stringify(obj))
: This function parses a JSON string into a JavaScript object. However, using JSON.parse()
with JSON.stringify(obj)
is not the most efficient way to merge two objects because it creates a new object each time and then recursively calls itself for each property in the object..extend(true, obj)
: This function is part of the jQuery library (specifically, .extend()
function) that merges multiple objects into one. The true
parameter indicates that the function should merge all properties from the source object(s) into the target object.Pros and Cons
Object.assign()
:JSON.parse(JSON.stringify(obj))
:.extend(true, obj)
(jQuery):Object.assign()
due to the additional overhead.Special JavaScript Feature/Syntax
The benchmark uses the $
symbol to reference jQuery's extend()
function, which is not a standard JavaScript feature but part of the jQuery library. This allows users who have jQuery included in their project to use this function without having to include it manually.
Other Alternatives
Alternative methods for object assignment or merging in JavaScript include:
.merge()
: A function from the lodash
library that provides a fast and efficient way to merge objects..assignIn()
: A method of the Lodash library (specifically, the assignIn()
function) that allows you to assign properties from one object to another in a deep, recursive manner.Note: These alternatives require including additional libraries (Lodash or jQuery), which may not be desirable for all projects.