[V8] Object & array copying
import { createBenchmark } from "./benchmark";
class MyArray extends Array {}
const SIZE = 100;
const obj: Record<string, number> = {};
/**
* {
* _0: 0,
* _1: 1,
* _2: 2,
* ...
* }
*/
const array = [];
/**
* [
* '_0', 0,
* '_1', 1,
* '_2', 2,
* ...
* }
*/
for (let i = 0; i < SIZE; i++) {
obj["_" + i] = i;
array.push("_" + i, i);
}
(function doBenchmarks(benchmark) {
(function benchmark1(obj, timer) {
let sum = 0;
while (timer()) {
for (const key in obj) {
sum += obj[key];
}
}
})(obj, benchmark("property"));
(function benchmark1(obj, timer) {
let sum = 0;
while (timer()) {
const copy = { ...obj };
for (const key in copy) {
sum += copy[key];
}
}
})(obj, benchmark("property with copy"));
(function benchmark2(array, timer) {
let sum = 0;
while (timer()) {
for (let i = 0; i < array.length; i += 2) {
sum += array[i] as number;
}
}
})(array, benchmark("array"));
(function benchmark2(array, timer) {
let sum = 0;
while (timer()) {
const copy = array.slice();
for (let i = 0; i < copy.length; i += 2) {
sum += copy[i] as number;
}
}
})(array, benchmark("array with copy"));
benchmark.report();
})(createBenchmark("iteration"));
From the result we can see that, using array.slice()
to copy a array is quite light weight operation, it doesn't affect performance that much.
But using {...obj}
is expensive, it affect performance by a lot.
It is due to the hidden class of the object, everytime you push a new prop into object it will create a new hidden class.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2020-11-13 [Spring Pattern] Builder pattern
2019-11-13 [Javascript] Check Promise is Promise
2019-11-13 [Javascript] Use requestIdleCallback to schedule JavaScript tasks at an optimal time
2019-11-13 [Javascript] Convert a callback based async operation into a Promise based
2017-11-13 [Python] String Formatting
2017-11-13 [TypeScript] Shallow copy object by using spread opreator
2017-11-13 [TypeScript] Model Alternatives with Discriminated Union Types in TypeScript