简体   繁体   中英

Improve mapping performance

I'm mapping values that I receive from an ajax call. It works pretty well, but it is still not fast enough in ie7 (I'm getting a slow script warning).

I can't figure out any way to make this faster. I've tried using native javascript functions as well, but the speed improvement was negligible. Do you guys have any ideas?

var $audit = $('#audit');

$.each(data, function (i, val) {

    if (val != null && val !== '0') {

        $audit.find('input[type="checkbox"].' + i).attr('checked', val == 1);
        $audit.find('input[type="text"].' + i).val(val);
        $audit.find('select.' + i).val(val);
    }

});

Some psuedo-html:

<div id="audit">
    <input type="text" class="foo1" />
    <input type="checkbox" class="foo2" />
    <select class="foo3">
        <option value="1">1</option>
    </select>
</div>

I dont know if it will help that much but you could cache your inputs + select and just filter that instead of finding the "same" element over and over again and just filter the specific element in a much smaller collection:

var $audit = $('#audit'),
    $inputs = $audit.find('input, select');

$.each(data, function (i, val) {
    if (val != null && val !== '0') {
        var current = $inputs.filter('.' + i);
        if(current.is(":checkbox") {
            current.attr('checked', val === 1);
        } else {
            current.val(val);
        }
    }
});

You can try to use knockout.js for your purposes. It may be faster.

This is an example of data binding: http://knockoutjs.com/examples/controlTypes.html

Per iteration, it's not too surprising that its slow when the scope chain keeps entering and leaving the DOM. However that the loop is taking a long time begs the question: how many of these divs are on the page? If it's more than around 50, then you've got a UI design issue.

To get this to go significantly faster really equires a radical redisgn of the code. If it were me, I'd build up an HTML framgent containing the repeating divs as a javascript string then splice it into the page using a single createElement/setting the innerHTML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM