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] BundleWriter: Improve performance #534

Merged
merged 5 commits into from
Oct 22, 2020
Merged
Changes from 3 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
15 changes: 11 additions & 4 deletions lib/lbt/bundle/BundleWriter.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


const NL = "\n";
const ENDS_WITH_NEW_LINE = /(^|\r\n|\r|\n)[ \t]*$/;
const ENDS_WITH_NEW_LINE = /(\r\n|\r|\n)[ \t]*$/;

/**
* A filtering writer that can count written chars and provides some convenience
Expand All @@ -20,11 +20,17 @@ class BundleWriter {
this.segments = [];
this.currentSegment = null;
this.currentSourceIndex = 0;
this.endsWithNewLine = true; // Initially we don't need a new line
}

write(...str) {
let writeBuf = "";
for ( let i = 0; i < str.length; i++ ) {
this.buf += str[i];
writeBuf += str[i];
}
if ( writeBuf.length >= 1 ) {
this.buf += writeBuf;
this.endsWithNewLine = ENDS_WITH_NEW_LINE.test(writeBuf);
Copy link
Member

Choose a reason for hiding this comment

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

This can give wrong results when write is called with blanks or tabs only. In that case, the old endsWithNewLine flag must be taken into account as well.

Correct would be something like

  ENDS_WITH_NEW_LINE.test(writeBuf) || (this.endsWithNewLine && !writeBuf.trim())

Instead of the trim(), one could use another RegExp /^[ \t]*$/

Copy link
Member Author

Choose a reason for hiding this comment

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

Sounds right 👍🏻
As there were no dedicated unit tests, I've added one to cover the whole class.

}
}

Expand All @@ -33,12 +39,13 @@ class BundleWriter {
this.buf += str[i];
}
this.buf += NL;
this.endsWithNewLine = true;
}

ensureNewLine() {
// TODO this regexp might be quite expensive (use of $ anchor on long strings)
if ( !ENDS_WITH_NEW_LINE.test(this.buf) ) {
if ( !this.endsWithNewLine ) {
this.buf += NL;
this.endsWithNewLine = true;
}
}

Expand Down