Skip to content

Commit

Permalink
Implement SourceMapSource.buffer for efficient size computation
Browse files Browse the repository at this point in the history
The `Source.size` method computes the size from the buffer length,
where the default `Source.buffer` method allocates a new buffer
from the string source. By implementing `SourceMapSource.buffer`
this allocation is avoided, as a buffer representation is available
on the instance. This results in a noticeable performance improvement
for stats computation in Webpack, where chunk sizes are obtained
from `Source.size`.
  • Loading branch information
JoostK authored and sokra committed Aug 2, 2021
1 parent a23222d commit aa8a753
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/SourceMapSource.js
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,11 @@ class SourceMapSource extends Source {
];
}

buffer() {
this._ensureValueBuffer();
return this._valueAsBuffer;
}

source() {
this._ensureValueString();
return this._valueAsString;
Expand Down
23 changes: 23 additions & 0 deletions test/SourceMapSource.js
Original file line number Diff line number Diff line change
Expand Up @@ -426,4 +426,27 @@ describe("SourceMapSource", () => {
}
`);
});

it("provides buffer when backed by string", () => {
const sourceMapSource = new SourceMapSource("source", "name");

const buffer1 = sourceMapSource.buffer();
expect(buffer1.length).toBe(6);

const buffer2 = sourceMapSource.buffer();
expect(buffer2).toBe(buffer1);
});

it("provides buffer when backed by buffer", () => {
const sourceMapSource = new SourceMapSource(
Buffer.from("source", "utf-8"),
"name"
);

const buffer1 = sourceMapSource.buffer();
expect(buffer1.length).toBe(6);

const buffer2 = sourceMapSource.buffer();
expect(buffer2).toBe(buffer1);
});
});

0 comments on commit aa8a753

Please # to comment.