Simple function that uses a lot of memory

I am using local storage because after the click, the page is reloaded, so I can keep track of the last clicked item.

As you can see, I tried to clear the localStorage to reduce the used memory, but it is already 1.000.000K in less than 10 minutes of use.

Is this script updating these variables in different places every time my page is reloaded?
What happens to him using this memory? This is my entire code.

This is an extension I'm building for chrome, it picks an option and clicks a button, the button submits the form, reloads the page, and it runs over and over again.

var last = localStorage.getItem('last');
var current = getNext(last);
var prox = getNext(current);

localStorage.clear();

$('select[name="myselect"] option').each(function(){
    if($(this).val().indexOf(current)>-1){
        $(this).prop('selected', true);
        $('.abc').first().click();
        localStorage.setItem('last',current);
    }
});

function getNext(current){
    var arrIds = ['227','228','229','230','231','232'];
    return arrIds[arrIds.indexOf(current)+1] || '227';
}

      

Updated code without var declarations, which drastically reduced memory consumption, but memory rises over time (after ten minutes from 160.000K to 240.000K):

$('select[name="myselect"] option').each(function(){
    if($(this).val().indexOf(getNext(localStorage.getItem('last')))>-1){
        $(this).prop('selected', true);
        $('.abc').first().click();
        localStorage.setItem('last',getNext(localStorage.getItem('last')));
    }
});

function getNext(current){
    var arrIds = ['227','228','229','230','231','232'];
    return arrIds[arrIds.indexOf(current)+1] || '227';
}

      

+3


source to share


1 answer


As per the discussion in the comments below, the problem comes from jQuery itself. The exact reason is not yet known, but jQuery seems to have retained data that is not being returned when the form is submitted.

This is probably partly due to the fact that it is a Chrome extension, since typically, when updating, the browser frees all memory, including globals.



jQuery creates a lot of potential for memory leaks by storing data and closures in a global reference called jQuery.cache

. If it is not cleaned up properly, leaks abound.

Since you're building a Chrome extension, you don't have to force you to use jQuery a lot, since you don't have to worry about browser incompatibility with browsers like IE6 and 7. By using the DOM API directly without such dependencies, the overall code will be smaller and much faster.

+4


source







All Articles