Skip to content
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

Perf: cache iconv decoder #2391

Merged
merged 3 commits into from
Jan 23, 2024
Merged
Changes from 2 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
27 changes: 24 additions & 3 deletions lib/parsers/string.js
Original file line number Diff line number Diff line change
@@ -1,21 +1,42 @@
'use strict';

const Iconv = require('iconv-lite');
const LRU = require('lru-cache');

exports.decode = function(buffer, encoding, start, end, options) {
const decoderCache = new LRU({
max: 500,
});

exports.decode = function (buffer, encoding, start, end, options) {
if (Buffer.isEncoding(encoding)) {
return buffer.toString(encoding, start, end);
}

const decoder = Iconv.getDecoder(encoding, options || {});
// Optimize for common case: encoding="short_string", options=undefined.
Copy link
Contributor Author

@sandinmyjoints sandinmyjoints Jan 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I figure encoding is probably constant for most users. For my use case, it's always "cesu8" (for utf8mb3).

let decoder;
if (!options) {
decoder = decoderCache.get(encoding);
if (!decoder) {
decoder = Iconv.getDecoder(encoding);
decoderCache.set(encoding, decoder);
}
} else {
const decoderArgs = { encoding, options };
const decoderKey = JSON.stringify(decoderArgs);
decoder = decoderCache.get(decoderKey);
if (!decoder) {
decoder = Iconv.getDecoder(decoderArgs.encoding, decoderArgs.options);
decoderCache.set(decoderKey, decoder);
}
}

const res = decoder.write(buffer.slice(start, end));
const trail = decoder.end();

return trail ? res + trail : res;
};

exports.encode = function(string, encoding, options) {
exports.encode = function (string, encoding, options) {
if (Buffer.isEncoding(encoding)) {
return Buffer.from(string, encoding);
}
Expand Down
Loading