Skip to content

Commit 081918b

Browse files
committed
add decode-string.ts
1 parent 73c9984 commit 081918b

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

benchmark/decode-string.ts

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/* eslint-disable no-console */
2+
import { utf8Encode, utf8Count, utf8Decode } from "../src/utils/utf8";
3+
import { utf8DecodeWasm } from "../src/wasmFunctions";
4+
5+
// @ts-ignore
6+
import Benchmark from "benchmark";
7+
8+
const textDecoder = new TextDecoder();
9+
10+
const dataSet = [10, 100, 200, 1_000, 10_000, 100_000].map((n) => {
11+
return "a".repeat(n);
12+
});
13+
14+
for (const str of dataSet) {
15+
const byteLength = utf8Count(str);
16+
const bytes = new Uint8Array(new ArrayBuffer(byteLength));
17+
utf8Encode(str, bytes, 0);
18+
19+
console.log(`\n## string length=${str.length} byteLength=${byteLength}\n`);
20+
21+
const suite = new Benchmark.Suite();
22+
23+
const N = Math.round(100_0000 / str.length);
24+
25+
// use the result to avoid void-context optimizations
26+
let count = 0;
27+
28+
suite.add("utf8Decode", () => {
29+
if (utf8Decode(bytes, 0, byteLength) !== str) {
30+
throw new Error("wrong result!");
31+
}
32+
});
33+
34+
suite.add("utf8DecodeWasm", () => {
35+
if (utf8DecodeWasm(bytes, 0, byteLength) !== str) {
36+
throw new Error("wrong result!");
37+
}
38+
});
39+
40+
suite.add("TextDecoder", () => {
41+
if (textDecoder.decode(bytes.subarray(0, byteLength)) !== str) {
42+
throw new Error("wrong result!");
43+
}
44+
});
45+
suite.on("cycle", (event: any) => {
46+
console.log(String(event.target));
47+
});
48+
49+
suite.run();
50+
}

0 commit comments

Comments
 (0)