简体   繁体   中英

How do I replace filtering an object with each & if

At the moment my code works, however it's very slow. The issue is with filtering object visits at the moment I'm going trough every item of visits and showing output based on if .

Would it be faster to use visits.filter ? If yes. How to tweak my function? Thanks

chrome.history.search(options, function(history) {
    $.each(history, function(i, item) {
        var itemTime = new Date(item.lastVisitTime)

        if (item.visitCount > 0) {
            $.each(history, function(i, item) {
                chrome.history.getVisits({ url: item.url }, function(visits) {

                    $.each(visits, function(i, visit) {

                        if (visit.visitTime > startTime && visit.id == item.id) {
                            var visiTime = new Date(visit.visitTime)
                            //console.log(visit)
                            console.log(visiTime + ' ' + item.url)
                        }

                    })
                })
            })
        } else {
            console.debug(itemTime + ' ' + item.url)
        }
    })
})

If you want to speed up your function, I recommand you to use a for loop with pre-calculated length . It is on average the faster loop known.

var len = a.length, i=0;
for(i; i < len ; i++){
    if (i>0)
        e = a[i];
}

TESTS

You can find here and here some tests, that show pre-calculated for loop vs JQuery each , uncached for loop and for loop .

Here a test classic for if vs filter .

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