Skip to content

Commit 2f0b78c

Browse files
committed
Improve performance of arrayBufferToBinaryString
* Skip expensive buffer overflows * Use TextDecoder when possible to speed up conversion
1 parent 56e2ff7 commit 2f0b78c

File tree

1 file changed

+24
-12
lines changed

1 file changed

+24
-12
lines changed

src/modules/addimage.js

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,10 @@ import { atob, btoa } from "../libs/AtobBtoa.js";
4343

4444
var UNKNOWN = "UNKNOWN";
4545

46+
// Heuristic limit after which String.fromCharCode will start to overflow.
47+
// Need to change to StringDecoder.
48+
var ARRAY_BUFFER_LIMIT = 6e6;
49+
4650
var imageFileTypeHeaders = {
4751
PNG: [[0x89, 0x50, 0x4e, 0x47]],
4852
TIFF: [
@@ -730,20 +734,28 @@ import { atob, btoa } from "../libs/AtobBtoa.js";
730734
var arrayBufferToBinaryString = (jsPDFAPI.__addimage__.arrayBufferToBinaryString = function(
731735
buffer
732736
) {
733-
try {
734-
return atob(btoa(String.fromCharCode.apply(null, buffer)));
735-
} catch (e) {
736-
if (
737-
typeof Uint8Array !== "undefined" &&
738-
typeof Uint8Array.prototype.reduce !== "undefined"
739-
) {
740-
return new Uint8Array(buffer)
741-
.reduce(function(data, byte) {
742-
return data.push(String.fromCharCode(byte)), data;
743-
}, [])
744-
.join("");
737+
// Skip direct conversion as it might take many hundred milliseconds before throwing.
738+
if (buffer.length < ARRAY_BUFFER_LIMIT) {
739+
try {
740+
return atob(btoa(String.fromCharCode.apply(null, buffer)));
741+
} catch (e) {
742+
// Buffer was overflown, fall back to other methods
745743
}
746744
}
745+
// Text decoder is much faster than string concatenation or reduce/join.
746+
if (typeof TextDecoder !== "undefined") {
747+
var decoder = new TextDecoder("ascii");
748+
return decoder.decode(buffer);
749+
} else if (
750+
typeof Uint8Array !== "undefined" &&
751+
typeof Uint8Array.prototype.reduce !== "undefined"
752+
) {
753+
return new Uint8Array(buffer)
754+
.reduce(function(data, byte) {
755+
return data.push(String.fromCharCode(byte)), data;
756+
}, [])
757+
.join("");
758+
}
747759
});
748760

749761
/**

0 commit comments

Comments
 (0)