This code is executed very often, so I'm wondering if it's already ideal or if it's possible to optimize it further.
var highlightLinks = function(e)
{
var anchors = e.target.getElementsByTagName("a");
let file = Components.classes["@mozilla.org/file/directory_service;1"]
.getService(Components.interfaces.nsIProperties)
.get("ProfD", Components.interfaces.nsIFile);
file.append("test.sqlite");
var storageService = Components.classes["@mozilla.org/storage/service;1"]
.getService(Components.interfaces.mozIStorageService);
var conn = storageService.openDatabase(file);
var statement = conn.createStatement("select * from links where url=?1");
for (var i = 0; i < anchors.length; i++) {
statement.bindStringParameter(0, anchors[i].href);
statement.executeAsync({
anchorIndex: i,
handleResult: function(aResultSet) {
for (let row = aResultSet.getNextRow();
row;
row = aResultSet.getNextRow()) {
let value = row.getResultByName("url");
if (value == anchors[this.anchorIndex]) {
anchors[this.anchorIndex].innerHTML += "+";
}
}
},
handleError: function(aError) {
print("Error: " + aError.message);
},
handleCompletion: function(aReason) {
if (aReason != Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED)
print("Query canceled or aborted!");
}
});
}
statement.finalize();
conn.close();
}
window.addEventListener("DOMContentLoaded", highlightLinks, false);
1 Answer 1
I believe you could improve your code by using prototypes like this:
function handler(anchorIndex, anchor) {
this.anchorIndex = anchorIndex;
this.anchor = anchor;
}
handler.prototype = {
handleResult: function(aResultSet) {
for (let row = aResultSet.getNextRow();
row;
row = aResultSet.getNextRow()) {
let value = row.getResultByName("url");
if (value == anchor) {
anchor.innerHTML += "+";
}
}
},
handleError: function(aError) {
print("Error: " + aError.message);
},
handleCompletion: function(aReason) {
if (aReason != Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED) {
print("Query canceled or aborted!");
}
}
};
Instead of creating a new object, which has to create new instances of the same functions, you create those functions once. This will improve performance and reduce memory usage across the board verified using http://jsperf.com/new-function-vs-object
Your for loop would be drastically reduced to look like
for (var i = 0; i < anchors.length; i++) {
statement.bindStringParameter(0, anchors[i].href);
statement.executeAsync(new handler(i, anchors[i]));
}
EDIT: You'll find this method of creating new instances of objects is faster in IE7-9 by ~3x, and roughly 2x as fast in FF5. My dev Chrome shows strange results in that the original method is 20% as fast as IE, yet shows ~155x improvement (10x faster than all other browsers) when using the prototype way.