forked from exceljs/exceljs
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
browser: use TextDecoder and TextEncoder for buffer
Doing a profiling in chrome dev tools shows that the `Buffer.toString()` and `Buffer.from(string)` is using unexpected long cpu time. With the native TextDecoder and TextEncoder it can get much faster in browsers supporting it. On browsers not supporting TextDecoder, like Internet Explorer, `Buffer.toString()` and `Buffer.from(string)` would not be changed. References: feross/buffer#268 feross/buffer#60 https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder
- Loading branch information
Showing
3 changed files
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
/* eslint-disable node/no-unsupported-features/node-builtins */ | ||
// Note: this is included only in browser | ||
if (typeof TextDecoder !== 'undefined' || typeof TextEncoder !== 'undefined') { | ||
const {Buffer} = require('buffer'); | ||
if (typeof TextEncoder !== 'undefined') { | ||
const textEncoder = new TextEncoder('utf-8'); | ||
const {from} = Buffer; | ||
Buffer.from = function(str, encoding) { | ||
if (typeof str === 'string') { | ||
if (encoding) { | ||
encoding = encoding.toLowerCase(); | ||
} | ||
if (!encoding || encoding === 'utf8' || encoding === 'utf-8') { | ||
return from.call(this, textEncoder.encode(str).buffer); | ||
} | ||
} | ||
return from.apply(this, arguments); | ||
}; | ||
} | ||
if (typeof TextDecoder !== 'undefined') { | ||
const textDecoder = new TextDecoder('utf-8'); | ||
const {toString} = Buffer.prototype; | ||
Buffer.prototype.toString = function(encoding, start, end) { | ||
if (encoding) { | ||
encoding = encoding.toLowerCase(); | ||
} | ||
if (!start && end === undefined && | ||
(!encoding || encoding === 'utf8' || encoding === 'utf-8')) { | ||
return textDecoder.decode(this); | ||
} | ||
return toString.apply(this, arguments); | ||
}; | ||
} | ||
} |