-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring-concat.js
More file actions
124 lines (94 loc) · 2.46 KB
/
string-concat.js
File metadata and controls
124 lines (94 loc) · 2.46 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
const benchmark = require('benchmark')
const suite = new benchmark.Suite()
let N = 100;
function simpleConcat() {
let str = '';
for (let i = 0; i < N; i++) {
str += 'longerText to make sure no funky stuff is happening';
}
return str;
}
function joinConcat() {
let arr = [];
for (let i = 0; i < N; i++) {
arr.push('longerText to make sure no funky stuff is happening');
}
return arr.join('');
}
const M = 12;
function bufferedConcat() {
let str = '';
let buf = '';
for (let i = 0; i < N; i++) {
buf += 'longerText to make sure no funky stuff is happening';
if (buf.length >= M) {
str += buf;
buf = '';
}
}
str += buf;
return str;
}
function bufferedConcat2() {
let buffs = [];
let buf = Buffer.from('','utf8');
let len=0;
for (let i = 0; i < N; i++) {
buffs.push(Buffer.from('longerText to make sure no funky stuff is happening'));
// len+='longerText to make sure no funky stuff is happening'.length;
}
return Buffer.concat(buffs).toString("utf8")
}
// warmup
let str1 = simpleConcat();
let str2 = joinConcat();
let str3 = bufferedConcat();
let str4 = bufferedConcat2();
console.log("Str4?", str4);
if (str3 !== str1) throw new Error('Bad buffered concat.');
if (str4 !== str1) throw new Error('Bad buffered2 concat.');
/*console.time('+=');
for (let i = 0; i < 10; i++) str1 = simpleConcat();
console.timeEnd('+=');
console.time('push/join');
for (let i = 0; i < 10; i++) str2 = joinConcat();
console.timeEnd('push/join');
console.time('buffered +=');
for (let i = 0; i < 10; i++) str3 = bufferedConcat();
console.timeEnd('buffered +=');
console.time('buffered2 +=');
for (let i = 0; i < 10; i++) str4 = bufferedConcat2();
console.timeEnd('buffered2 +=');*/
suite.add('+=', function () {
str1 = simpleConcat();
})
suite.add('push(/join', function () {
str2 = joinConcat();
})
suite.add('buffered', function () {
str3 = bufferedConcat();
})
suite.add('buffered2', function () {
str4 = bufferedConcat2();
})
suite.add('+=', function () {
N = 1000000;
str1 = simpleConcat();
})
suite.add('push(/join', function () {
N = 1000000;
str2 = joinConcat();
})
suite.add('buffered', function () {
N = 1000000;
str3 = bufferedConcat();
})
suite.add('buffered2', function () {
N = 1000000;
str4 = bufferedConcat2();
})
suite.on('cycle', cycle)
suite.run()
function cycle (e) {
console.log(e.target.toString())
}