Skip to content

Improve performance of arrayBufferToBinaryString #3121

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 16 additions & 13 deletions src/modules/addimage.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,11 @@ import { atob, btoa } from "../libs/AtobBtoa.js";

var UNKNOWN = "UNKNOWN";

// Heuristic selection of a good batch for large array .apply. Not limiting make the call overflow.
// With too small batch iteration will be slow as more calls are made,
// Higher values cause larged and slower garbage collection.
var ARRAY_APPLY_BATCH = 8192;

var imageFileTypeHeaders = {
PNG: [[0x89, 0x50, 0x4e, 0x47]],
TIFF: [
Expand Down Expand Up @@ -730,20 +735,18 @@ import { atob, btoa } from "../libs/AtobBtoa.js";
var arrayBufferToBinaryString = (jsPDFAPI.__addimage__.arrayBufferToBinaryString = function(
buffer
) {
try {
return atob(btoa(String.fromCharCode.apply(null, buffer)));
} catch (e) {
if (
typeof Uint8Array !== "undefined" &&
typeof Uint8Array.prototype.reduce !== "undefined"
) {
return new Uint8Array(buffer)
.reduce(function(data, byte) {
return data.push(String.fromCharCode(byte)), data;
}, [])
.join("");
}
var out = "";
var u8buf = new Uint8Array(buffer);
for (var i = 0; i < u8buf.length; i += ARRAY_APPLY_BATCH) {
// Limit the amount of characters being parsed to prevent overflow.
// Note that while TextDecoder would be faster, it does not have the same
// functionality as fromCharCode with any provided encodings as of 3/2021.
out += String.fromCharCode.apply(
null,
u8buf.subarray(i, i + ARRAY_APPLY_BATCH)
);
}
return out;
});

/**
Expand Down