Skip to content

Commit

Permalink
Use cached TextEncoder/-Decoder instances (#22)
Browse files Browse the repository at this point in the history
  • Loading branch information
achim-k authored Jan 2, 2024
1 parent eb91735 commit 60de1d9
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
5 changes: 3 additions & 2 deletions src/CdrReader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,14 @@ type ArrayValueGetter =
| "getFloat32"
| "getFloat64";

const textDecoder = new TextDecoder("utf8");

export class CdrReader {
private view: DataView;
private littleEndian: boolean;
private hostLittleEndian: boolean;
private eightByteAlignment: number; // Alignment for 64-bit values, 4 on CDR2 8 on CDR1
private isCDR2: boolean;
private textDecoder = new TextDecoder("utf8");

/** Origin offset into stream used for alignment */
private origin = 0;
Expand Down Expand Up @@ -174,7 +175,7 @@ export class CdrReader {
return "";
}
const data = new Uint8Array(this.view.buffer, this.view.byteOffset + this.offset, length - 1);
const value = this.textDecoder.decode(data);
const value = textDecoder.decode(data);
this.offset += length;
return value;
}
Expand Down
5 changes: 3 additions & 2 deletions src/CdrWriter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ export type CdrWriterOpts = {
kind?: EncapsulationKind;
};

const textEncoder = new TextEncoder();

export class CdrWriter {
static DEFAULT_CAPACITY = 16;
static BUFFER_COPY_THRESHOLD = 10;
Expand All @@ -21,7 +23,6 @@ export class CdrWriter {
private buffer: ArrayBuffer;
private array: Uint8Array;
private view: DataView;
private textEncoder = new TextEncoder();
private offset: number;
/** Origin offset into stream used for alignment */
private origin: number;
Expand Down Expand Up @@ -167,7 +168,7 @@ export class CdrWriter {
this.uint32(strlen + 1); // Add one for the null terminator
}
this.resizeIfNeeded(strlen + 1);
this.textEncoder.encodeInto(value, new Uint8Array(this.buffer, this.offset, strlen));
textEncoder.encodeInto(value, new Uint8Array(this.buffer, this.offset, strlen));
this.view.setUint8(this.offset + strlen, 0);
this.offset += strlen + 1;
return this;
Expand Down

0 comments on commit 60de1d9

Please sign in to comment.