JavaScript append

I’ve started my JavaScript journey by creating a tool to parse localized string files for iOS. We often get these files back from the translator and there are minor errors in them.

The only problem is that Xcode will only flag as a file as “corrupt.” It won’t tell you what the error is or even what line the error is on. The most common error is a missing semi-colon at the end of the line, although mishandled quotes is also an issue.

Eyeballing this errors is hard because the strings are often in foreign languages with the non-American characters and the files are a couple of thousand lines long. So I’m writing a small web page to read a specified file and display it with the erroneous lines highlighted in red.

The issue I which I quickly ran into was the append function (+=) in Javascript is horribly slow.

// bad, don't do this, especially in a loop
results.innerHTML += '<div>' + newComment + '<br></div>';

I found a buffering function which really speeds up the process. This code was posted over five years ago, so perhaps there’s a better way, but this was very speedy indeed:

function StringBuffer() {
this.buffer = [];
}
StringBuffer.prototype.append = function append(string) {
this.buffer.push(string);
return this;
};
StringBuffer.prototype.toString = function toString() {
return this.buffer.join("");
}

var buffer = new StringBuffer();
// processing loop
// do work to create newComment values
buffer.append('<div class="comment">');
buffer.append(newComment);
buffer.append('</div>');
// end of loop

// now, add the buffer all at once to the HTML
resultsDiv.innerHTML = buffer.toString();
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s