-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfs_test.html
More file actions
393 lines (338 loc) · 13.5 KB
/
fs_test.html
File metadata and controls
393 lines (338 loc) · 13.5 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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>FS Benchmark</title>
<style>
body { font-family: sans-serif; padding: 20px; }
.result { margin-top: 20px; }
table { border-collapse: collapse; width: 100%; max-width: 800px; }
th, td { border: 1px solid #ccc; padding: 8px; text-align: center; }
th { background-color: #f4f4f4; }
.loading { color: gray; }
#count {
width: 50px
}
#size {
width: 100px
}
</style>
</head>
<body>
<h1>Filesystem Test (Write & Read)</h1>
<input id="all" type="checkbox"><br/>
<input id="inmemory" type="checkbox"> InMemory<br/>
<input id="localstorage" type="checkbox"> LocalStorage<br/>
<input id="indexedDB" type="checkbox"> IndexedDB<br/>
<input id="opfs" type="checkbox"> OPFS<br/>
<br/>
Files count: <input id="count" min="1" type="number" value="1"><br/>
Size: <input id="size" type="number" min="0" value="1024"> KB<br/>
Check size <input id="check_size" type="checkbox" checked="true"><br/><br/>
<button id="runBtn">Run test</button>
<div class="result">
<h2>Result</h2>
<table id="resultsTable">
<thead>
<tr>
<th>Backend</th>
<th>Write (ms)</th>
<th>Read (ms)</th>
<th>Info</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<script>
const $ = document.querySelector.bind(document);
const FILENAME = 'test.txt';
let localStorageFreeSpace = 0
let FILEDATA = '';
function addResultRow(name, writeTime, readTime, info) {
const tbody = document.querySelector('#resultsTable tbody');
const tr = document.createElement('tr');
tr.innerHTML = `<td>${name}</td><td>${writeTime}</td><td>${readTime}</td><td>${info}</td>`;
tbody.appendChild(tr);
}
function testMaxMemory() {
let size = 1024 * 1024; // 1MB
let buffer = null;
try {
while(true) {
buffer = new Uint8Array(size);
size *= 2;
}
} catch(e) {
return size / 1024 / 1024;
}
}
function getObjectMB(obj) {
if(!obj) return 0;
let bytes = 0;
if(obj instanceof ArrayBuffer || (typeof obj === 'object' && 'buffer' in obj && obj.buffer instanceof ArrayBuffer)) {
bytes = obj.byteLength || obj.buffer.byteLength;
} else if(obj instanceof ArrayBuffer) {
bytes = obj.byteLength;
} else if(obj instanceof Blob) {
bytes = obj.size;
} else if(typeof obj == 'object') {
try {
const str = JSON.stringify(obj);
bytes = new TextEncoder().encode(str).byteLength;
} catch(e) {
console.warn("Невозможно определить размер объекта");
return 0;
}
} else if(typeof obj == 'string') {
bytes = new TextEncoder().encode(obj).byteLength;
} else {
bytes = 8;
}
const mb = bytes / (1024 * 1024);
return Math.round(mb * 10) / 10;
}
function getLocalStorageFreeSpace() {
return new Promise((resolve, reject) => {
const key = '__localStorageFreeSpaceTest';
let low = 0;
let high = 1024 * 1024; // start with 1mb
function tryWrite(size) {
try {
const str = 'x'.repeat(size);
localStorage.setItem(key, str);
localStorage.removeItem(key);
return true;
} catch (e) {
return false;
}
}
// We increase the upper limit until we reach the limit
const findUpperLimit = () => {
if(tryWrite(high)) {
high *= 2;
setTimeout(findUpperLimit, 0);
} else {
low = high / 2;
binarySearch();
}
};
// Binary search
const binarySearch = () => {
if(high - low <= 1024) {
localStorage.removeItem(key);
resolve(Math.floor(high / 1024));
return;
}
const mid = Math.floor((low + high) / 2);
if(tryWrite(mid))
low = mid;
else
high = mid;
setTimeout(binarySearch, 0);
};
findUpperLimit();
});
}
getLocalStorageFreeSpace().then(e => localStorageFreeSpace = e);
async function testInMemory() {
const count = Math.max(0, $('#count').value);
const checkSize = $('#check_size').checked??false;
const fs = {};
let start;
const info = checkSize ? `Total quota: ${testMaxMemory()} MB` : '';
start = performance.now();
for(let i=0;i<count;i++)
fs[FILENAME+i] = FILEDATA;
const write = performance.now() - start;
start = performance.now();
for(let i=0;i<count;i++){
const data = fs[FILENAME+i];
}
const read = performance.now() - start;
return { write, read, info };
}
async function testLocalStorage() {
const count = Math.max(0, $('#count').value);
const checkSize = $('#check_size').checked??false;
for(let i=0;i<count;i++)
localStorage.removeItem(FILENAME+i);
if(getObjectMB(FILEDATA) > 5) throw '';
const info = checkSize ? `Total quota: ${await getLocalStorageFreeSpace()} MB` : '';
let start = performance.now();
for(let i=0;i<count;i++)
localStorage.setItem(FILENAME+i, FILEDATA);
const write = performance.now() - start;
start = performance.now();
for(let i=0;i<count;i++){
const data = localStorage.getItem(FILENAME+i);
}
const read = performance.now() - start;
for(let i=0;i<count;i++)
localStorage.removeItem(FILENAME+i);
return { write, read, info };
}
async function testIndexedDB() {
const count = Math.max(0, $('#count').value);
const checkSize = $('#check_size').checked??false;
const DB_NAME = 'BenchmarkDB';
const STORE_NAME = 'files';
return new Promise((resolve) => {
const req = indexedDB.open(DB_NAME);
req.onupgradeneeded = (e) => {
const db = req.result;
if((!db.objectStoreNames.contains(STORE_NAME))) {
db.createObjectStore(STORE_NAME);
}
};
req.onsuccess = (e) => {
const db = req.result;
const writeStart = performance.now();
for(let i=0;i<count;i++){
const putReq = db.transaction(STORE_NAME, 'readwrite').objectStore(STORE_NAME).put(FILEDATA, FILENAME);
putReq.onsuccess = () => {
const write = performance.now() - writeStart;
const readStart = performance.now();
const getReq = db.transaction(STORE_NAME).objectStore(STORE_NAME).get(FILENAME);
getReq.onsuccess = async() => {
const read = performance.now() - readStart;
if(i == count-1){
// Size
let info = '';
if(checkSize){
if('estimate' in navigator.storage) {
const estimate = await navigator.storage.estimate();
const quota = estimate.quota;
const usage = estimate.usage;
info = `Total quota: ${(quota / (1024 * 1024)).toFixed(2)} MB<br/>Used: ${(usage / (1024 * 1024)).toFixed(2)} MB`;
} else {
info = 'No support(navigator.storage.esimate not exists)';
}
}
db.close();
indexedDB.deleteDatabase(DB_NAME);
resolve({ write, read, info });
}
};
};
}
};
});
}
async function testOPFS() {
const count = Math.max(0, $('#count').value);
const checkSize = $('#check_size').checked??false;
if((!navigator.storage || !navigator.storage.getDirectory)) {
throw new Error('OPFS doesnt support');
}
const root = await navigator.storage.getDirectory();
const handles = [];
// Write
const writeStart = performance.now();
for(let i=0;i<count;i++){
const handle = await root.getFileHandle(FILENAME+i, { create: true });
handles.push(handle);
const writable = await handle.createWritable();
await writable.write(FILEDATA);
await writable.close();
}
const write = performance.now() - writeStart;
// Read
const readStart = performance.now();
for(let i=0;i<count;i++){
const file = await handles[i].getFile();
const text = await file.text();
}
const read = performance.now() - readStart;
// Size
let info = '';
if(checkSize){
if('estimate' in navigator.storage) {
const estimate = await navigator.storage.estimate();
const quota = estimate.quota;
const usage = estimate.usage;
info = `Total quota: ${(quota / (1024 * 1024)).toFixed(2)} MB<br/>Used: ${(usage / (1024 * 1024)).toFixed(2)} MB`;
// console.log(`Total quota: ${(quota / (1024 * 1024)).toFixed(2)} MB`);
// console.log(`Used: ${(usage / (1024 * 1024)).toFixed(2)} MB`);
// console.log(`Remaining: ${((quota - usage) / (1024 * 1024)).toFixed(2)} MB`);
} else {
info = 'Size: no support(navigator.storage.esimate not exists)';
}
}
// Erase
for await(const [name, handle] of root.entries()) {
if(handle.kind == 'file' && name.startsWith(FILENAME)) {
await root.removeEntry(name);
}
}
return { write, read, info };
}
async function test(){
let size = parseInt(document.getElementById('size').value ?? 1024);
if(isNaN(size)) {
alert('Size is was NaN. Selected size: 1024');
size = 1024;
}
if(size > (1024 * 500)) {
if(!confirm(`Are you sure you're ready for this size?`)) return;
}
try{
FILEDATA = new Uint8Array(1024 * size)//'A'.repeat(1024 * size);
}catch{
}
$('#runBtn').disabled = true;
$('#resultsTable').querySelector('tbody').innerHTML = '';
const inmemory = $('#inmemory').checked;
const localstorage = $('#localstorage').checked;
const indexedDB = $('#indexedDB').checked;
const opfs = $('#opfs').checked;
try {
if(inmemory){
console.log("Testing InMemory...");
const mem = await testInMemory();
addResultRow("InMemory", mem.write.toFixed(2), mem.read.toFixed(2), mem.info);
}
if(localstorage) try{
console.log("Testing LocalStorage...");
const local = await testLocalStorage();
addResultRow("LocalStorage", local.write.toFixed(2), local.read.toFixed(2), local.info);
}catch(e){
console.error(e);
addResultRow("LocalStorage", '-', '-', `Error(limit ${localStorageFreeSpace}MB)`);
}
if(indexedDB){
console.log("Testing IndexedDB...");
const idb = await testIndexedDB();
addResultRow("IndexedDB", idb.write.toFixed(2), idb.read.toFixed(2), idb.info);
}
if(opfs) if(('storage' in navigator && 'getDirectory' in navigator.storage)) {
console.log("Testing OPFS...");
try {
const opfs = await testOPFS();
addResultRow("OPFS", opfs.write.toFixed(2), opfs.read.toFixed(2), opfs.info);
} catch(e) {
console.error(e);
if(location.protocol == 'file:') addResultRow("OPFS", "-", "-", "No support(file://)");
else addResultRow("OPFS", "-", "-", "No support");
}
} else {
addResultRow("OPFS", "-", "-", "Doesn't support");
}
} finally {
document.getElementById('runBtn').disabled = false;
}
}
$('#runBtn').addEventListener('click', test);
const fsb = ['inmemory', 'localstorage', 'indexedDB', 'opfs']
$('#all').addEventListener('click', () => {
fsb.forEach(e => $('#'+e).checked = $('#all').checked)
});
function dCheckbox(e){
if(fsb.filter(e => !$("#"+e).checked).length == 0) $("#all").checked = true;
else $("#all").checked = false;
}
fsb.forEach(e => $('#'+e).addEventListener('click', dCheckbox));
$('#all').click();
</script>
</body>
</html>