Javascript code too slow in Firefox extension using Storage service

前端 未结 3 1230
南笙
南笙 2021-01-26 02:45

I\'m running the following javascript code in firefox extension

highlightLinks: function(e) {

  var anchors = e.target.getElementsByTagName(\"a\");
  let file =         


        
3条回答
  •  温柔的废话
    2021-01-26 03:21

    It'll be faster if you pull the createStatement out of the loop, and reuse it, rebinding the parameters each time. The docs for storage say: "Note: If you need to execute a statement multiple times, caching the result of createStatement will give you a noticeable performance improvement because the SQL query does not need to be parsed each time."

    So instead of:

    for (var i = 0; i < anchors.length; i++) {
      var statement = conn.createStatement("select * from links where url=?1");
      statement.bindStringParameter(0, anchors[i].href);
      // ... do stuff with results
    

    write:

    var statement = conn.createStatement("select * from links where url=?1");
    for (var i = 0; i < anchors.length; i++) {
      statement.bindStringParameter(0, anchors[i].href);
      // ... do stuff with results
    

    Edit: Also, if you're using a recent Firefox, you can use their asynchronous API to avoid delaying the UI. Instead of calling executeStep, use executeAsync instead.

    statement.executeAsync({
      handleResult: function(aResultSet) {
        // ... do stuff with results
      },
    
      handleError: function(aError) {
        print("Error: " + aError.message);
      },
    
      handleCompletion: function(aReason) {
        if (aReason != Components.interfaces.mozIStorageStatementCallback.REASON_FINISHED)
          print("Query canceled or aborted!");
      }
    });
    

提交回复
热议问题