-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
96 lines (88 loc) · 2.67 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import * as path from 'path';
import Benchmark from 'benchmark';
import structuredClonePolyfill from '@ungap/structured-clone';
import lodashCloneDeep from 'lodash.clonedeep';
import rfdc from 'rfdc';
import cloneDeep from 'clone-deep';
import { copy as fastestClone } from 'fastest-json-copy';
import cloneJSON from '../index';
const rfdcDefault = rfdc();
const rfdcProto = rfdc({ proto: true, circles: false });
function viaJSON(x: any): any {
return JSON.parse(JSON.stringify(x));
}
function naive(x: any): any {
if (typeof x === 'number' || typeof x === 'boolean' || typeof x === 'string' || x === null) {
return x;
} else if (Array.isArray(x)) {
return x.map(naive);
} else {
const ret: any = {};
for (const [k, v] of Object.entries(x)) {
ret[k] = naive(v);
}
return ret;
}
}
function bench(name: string, data: any): void {
console.log(`Running ${name} benchmark suite...`);
const suite = new Benchmark.Suite(name);
suite
.add('Native structuredClone', function () {
structuredClone(data);
})
.add('structuredClone polyfill', function () {
structuredClonePolyfill(data);
})
.add('JSON serialize/deserialize', function () {
viaJSON(data);
})
.add('Naive deep clone', function () {
naive(data);
})
.add('lodash.clonedeep', function () {
lodashCloneDeep(data);
})
.add('clone-deep', function () {
cloneDeep(data);
})
.add('rfdc (default)', function () {
rfdcDefault(data);
})
.add('rfdc (proto)', function () {
rfdcProto(data);
})
.add('fastest-json-copy', function () {
fastestClone(data);
})
.add('fast-json-clone (this package)', function () {
cloneJSON(data);
})
.on('cycle', function (event: Benchmark.Event) {
console.log(String(event.target));
})
.on('complete', function (this: typeof suite) {
console.log('Fastest is ' + this.filter('fastest').map('name'));
})
.run();
console.log(`Finish ${name} benchmark suite`);
}
const large = require(path.join(__dirname, '..', 'testdata', 'large.json'));
const medium = require(path.join(__dirname, '..', 'package.json'));
const small = {
str: 'hello',
num: 42,
bool: true,
null: null,
array: ['hello', 42, true, null],
object: {
str: 'hello',
num: 42,
bool: true,
null: null,
},
};
bench('LARGE', large);
bench('MEDIUM', medium);
bench('SMALL', small);
bench('EMPTY', {});