Skip to content

Commit 2138025

Browse files
committed
perf: speedup decodeLatin1 with atob
1 parent 3709fb6 commit 2138025

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

fallback/latin1.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,19 @@ import {
66
isHermes,
77
isDeno,
88
isLE,
9+
skipWeb,
910
} from './_utils.js'
1011

12+
const { atob } = globalThis
13+
const { toBase64: web64 } = Uint8Array.prototype
14+
1115
// See http://stackoverflow.com/a/22747272/680742, which says that lowest limit is in Chrome, with 0xffff args
1216
// On Hermes, actual max is 0x20_000 minus current stack depth, 1/16 of that should be safe
1317
const maxFunctionArgs = 0x20_00
1418

19+
// toBase64+atob path is faster on everything where fromBase64 is fast
20+
const useLatin1atob = web64 && atob && !skipWeb
21+
1522
export function asciiPrefix(arr) {
1623
let p = 0 // verified ascii bytes
1724
const length = arr.length
@@ -46,6 +53,18 @@ export function decodeLatin1(arr, start = 0, stop = arr.length) {
4653
stop |= 0
4754
const total = stop - start
4855
if (total === 0) return ''
56+
57+
if (
58+
useLatin1atob &&
59+
total >= 256 &&
60+
total < 1e8 &&
61+
arr.toBase64 === web64 &&
62+
arr.BYTES_PER_ELEMENT === 1
63+
) {
64+
const sliced = start === 0 && stop === arr.length ? arr : arr.subarray(start, stop)
65+
return atob(sliced.toBase64())
66+
}
67+
4968
if (total > maxFunctionArgs) {
5069
let prefix = ''
5170
for (let i = start; i < stop; ) {

single-byte.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ export function createSinglebyteEncoder(encoding, { mode = 'fatal' } = {}) {
105105
if (typeof s !== 'string') throw new TypeError(E_STRING)
106106
if (isLatin1) {
107107
// max limit is to not produce base64 strings that are too long
108-
if (s.length >= 1024 && s.length < 1e8 && useLatin1btoa) {
108+
if (useLatin1btoa && s.length >= 1024 && s.length < 1e8) {
109109
try {
110110
return Uint8Array.fromBase64(btoa(s)) // fails on non-latin1
111111
} catch {

0 commit comments

Comments
 (0)