Improve the Ref.prototype.toString method a tiny bit

When getting/creating a new `Ref` instance, via the static `Ref.get` method, we already need to compute a cache-key.
Since this key is identical to the format used by the `toString` method, we can avoid having to re-create that string (a lot) by also providing it to the `Ref` constructor.
This commit is contained in:
Jonas Jenwald 2026-07-22 13:21:29 +02:00
parent 0c8f67059e
commit 27a8002f7e

View File

@ -288,7 +288,10 @@ class Dict {
} }
class Ref { class Ref {
constructor(num, gen) { #str;
constructor(str, num, gen) {
this.#str = str;
this.num = num; this.num = num;
this.gen = gen; this.gen = gen;
} }
@ -296,10 +299,7 @@ class Ref {
toString() { toString() {
// This function is hot, so we make the string as compact as possible. // This function is hot, so we make the string as compact as possible.
// |this.gen| is almost always zero, so we treat that case specially. // |this.gen| is almost always zero, so we treat that case specially.
if (this.gen === 0) { return this.#str;
return `${this.num}R`;
}
return `${this.num}R${this.gen}`;
} }
static fromString(str) { static fromString(str) {
@ -311,18 +311,16 @@ class Ref {
if (!m || m[1] === "0") { if (!m || m[1] === "0") {
return null; return null;
} }
const num = parseInt(m[1], 10),
gen = !m[2] ? 0 : parseInt(m[2], 10);
// eslint-disable-next-line no-restricted-syntax // eslint-disable-next-line no-restricted-syntax
return (RefCache[str] = new Ref( return (RefCache[str] = new Ref(str, num, gen));
parseInt(m[1], 10),
!m[2] ? 0 : parseInt(m[2], 10)
));
} }
static get(num, gen) { static get(num, gen) {
const key = gen === 0 ? `${num}R` : `${num}R${gen}`; const str = gen === 0 ? `${num}R` : `${num}R${gen}`;
// eslint-disable-next-line no-restricted-syntax // eslint-disable-next-line no-restricted-syntax
return (RefCache[key] ||= new Ref(num, gen)); return (RefCache[str] ||= new Ref(str, num, gen));
} }
} }