在IE和FF中慢执行js [英] Slow executing js in IE and FF

查看:73
本文介绍了在IE和FF中慢执行js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个函数运行返回的json数据。它的速度非常快,但IE和FF速度很慢。关于如何改进这个的建议?返回的数据大约是15个对象。这会在顶部创建一堆锚点,每个标题下都有列表。

I have this function that runs over returned json data. It is really fast in chrome, but slow in IE and FF. Suggestions on how I might improve this? The data returned is about 15 objects. This creates a bunch of anchors at the top with lists under each heading.

function list_response(jsonData) {
    "use strict";
    var lists = document.getElementById("lists"), anchors = document.getElementById("anchors"), jItems = jsonData.items;
    jItems.sort(function (a, b) {
            return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
            });
    for (var i = 0; i < jItems.length; i++) {
        var pList = jItems[i], str = "", ank = "";
        str += '<span class="backtotop">[ <a href="#">Back to top</a> ]</span><br /><br /><br /><li class="title nodot"><a class="pHeader" name="' + pList.name + '"><h2>' + pList.name + '</h2></a></li>';
        ank += '<a class="pHeader" href="#' + pList.name + '">' + pList.name + '</a>&nbsp; ';
        lists.innerHTML += str;
        anchors.innerHTML += ank;

        for (var j = 0; j < jsonData.items[i]["videos"].length; j++) {
            var vList = jsonData.items[i]["videos"][j];
            var strs = "";
            strs += '<li class="nodot"><a href="https://www.site.org/videos/Video_Player.page?bctid=' + vList.id + '">' + vList.name + '</a></li>';
            lists.innerHTML += strs;
        }
    }
}


推荐答案

以下是您的代码版本,它结合了以下性能增强功能:

Here's a version of your code that combines the following performance enhancements:


  1. 仅在循环结束时添加一次innerHTML 。您希望尽可能多地避免这样做,因为每次添加该项时,它都会导致对该项中所有HTML的完整重新分析。这最大限度地减少了与DOM的事务数量,这可能是整个例程中最慢的部分。这个改进版本大大减少了DOM事务的数量。如果 jItems.length 20 且平均视频数为5,这会将DOM交易数量减少到占事务数量的1/50。

  2. 使用 .push()将字符串数据累积到一个数组中并执行 .join()最后不是每次都添加到字符串的末尾。 JS引擎通常可以比连接每个段更有效地连接大量字符串。

  3. 当将字符串数据累积到数组中时,不再需要初始化每个字符串。循环或子循环。

  4. 而不是获取 pList 然后有四个对 pList.name <的引用/ code>,只需获取一次名称值并直接使用它。

  5. 缓存 jItems [i] 在循环中因为它引用了几个地方,而不是每次重新计算它。

  6. 循环计算每个的len变量只需一次并比较而不是在每次迭代时重新计算它。

  7. 缓存 jItems [i] [videos] 一次在外循环而不是重做每次都在内循环中。

  8. 如果 jsonData.items 中有大量项目,那么排序算法不是由于必须重新计算小写字母,所以非常有效每个比较的每个名称。您可以在一次传递中预编译所有小写版本(每个项目一次),然后在排序算法中使用它们,而不是每次比较两个项目时都必须重做它们。

  1. Only add to innerHTML once at the end of the loop. You want to avoid doing that as often as you can because it causes an entire reparse of all the HTML in that item every time you add onto it. This minimizes the number of transactions with the DOM which can be the slowest part of the whole routine. This improved version cuts the number of DOM transactions a lot. If jItems.length was 20 and the average number of videos was 5, this would cut the number of DOM transactions to 1/50th the number of DOM transactions.
  2. Accumulate string data into an array with .push() and do a .join() at the very end rather than adding onto the end of the string every time. The JS engine can often join lots of strings at once much more efficiently than joining each segment piecemeal.
  3. When accumulating string data into arrays, there is no longer a need to initialize the temporaries on each loop or sub-loop.
  4. Rather than get pList and then have four references to pList.name, just get the name value once and use it directly.
  5. Cache jItems[i] in the loop because it's referenced several places rather than recalculating it every time.
  6. Calculate the len variable for each for loop just once and compare to that rather than recalculating it on every iteration.
  7. Cache jItems[i]["videos"] once in the outer loop rather than redoing it every time in the inner loop.
  8. If there are a large number of items in jsonData.items, then the sort algorithm isn't very efficient since it has to recalculate a lowercase version of each name for every comparison. You could prebuild all the lowercase versions in one pass (once per item) and then just use them in the sort algorithm rather than have to redo them every time two items are compared.

这些更改导致此代码:

function list_response(jsonData) {
    "use strict";
    var lists = document.getElementById("lists"), anchors = document.getElementById("anchors"), jItems = jsonData.items;
    var results = [], anks = [], vList, pListName, item, videoItem;
    // precache all lower case versions to make sorting faster
    var i, iLen = jItems.length, j, jLen;
    for (var i = 0; i < iLen; i++) {
        jItems[i].nameLower = jItems[i].name.toLowerCase();
    }
    jItems.sort(function (a, b) {
        return a.nameLower.localeCompare(b.nameLower);
    });
    for (i = 0; i < iLen; i++) {
        item = jItems[i];                   // cache for use in loops
        videoItem = item["videos"];      // cache for use in loops
        pListName = item.name;            // cache for use in multiple places
        results.push('<span class="backtotop">[ <a href="#">Back to top</a> ]</span><br /><br /><br /><li class="title nodot"><a class="pHeader" name="' + pListName + '"><h2>' + pListName + '</h2></a></li>');
        anks.push('<a class="pHeader" href="#' + pListName + '">' + pListName + '</a>&nbsp; ');

        for (j = 0, jLen = videoItem.length; j < jLen; j++) {
            vList = videoItem[j];
            results.push('<li class="nodot"><a href="https://www.site.org/videos/Video_Player.page?bctid=' + vList.id + '">' + vList.name + '</a></li>');
        }
    }
    lists.innerHTML += results.join("");
    anchors.innerHTML += anks.join("");
}

这篇关于在IE和FF中慢执行js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆