mortenstarck
mortenstarck

Reputation: 2803

DOM performance in Javascript

I have an question about performance of loading alot off DOM objects. First i have an array of the length of 9540, of something like this:

{"Id":144412,"GisX":55.50963,"GisY":9.77794}`)

The problem is not the loop, but the problem is then i load all the click event to the DOM, which takes 1200ms in Chrome(IE it takes 8700ms), the problem is in Leafletjs using markerCluster. But any idea to increase the performance.

for (var i = 0, obj; (obj = MarkerArrayDefs[i]); i++) {
    setMarker(obj.Id, obj.GisX, obj.GisY, i);
} //The for loop takes: 151.000ms
var markerList = [];

function setMarker(propId, lat, lng) {
    //var marker = new L.Marker([lat, lng]);
    var marker = new L.Marker([lat, lng], {
        icon: customIcon
    }).on('click', function () {
        var markeren = this;
        var popup = L.popup({
            offset: (new L.Point(-10, -47))
        }).setLatLng(markeren.getLatLng()).setContent('<div><span style="color: #4a6b0e; font-weight: bold;">Henter</span><br><img alt="Progress" src="' + ol.url("~/Content/Css/images/mapWaiting.gif") + '" id="imgProg"/></div>').openOn(folia.map);
        $.get(ol.url('~/ControllerHelper/MapContent/'), {
            id: propId,
            callType: searchfilters.ItemType
        }, function (data) {
            popup.setContent(data);
        });
    });
    markerList.push(marker);
    return false;
}
markers.addLayers(markerList); //This takes: 0.000ms.
map.addLayer(markers); // This is the problem: 1200.000ms

Update I have tried to use the suggestions given to me, but there's not alot of performance gainSee JSFiddle example This is the start point

Upvotes: 0

Views: 254

Answers (2)

Quonux
Quonux

Reputation: 2991

Don't use setContent because it is damn slow ,building the DOM nodes manually is maybe faster.

A very good tutorial to manipulate the DOM tree is here.

You can also circumvent the big DOM doom with the use of the canvas Element and some javascript magic.

Upvotes: 1

ErikE
ErikE

Reputation: 50251

Put the onclick event function on the parent element of your markers, not on each marker, and then within it determine which (if any) of the children was clicked. Then you have only a single event to wire up--this should also save some memory.

Also, a great way to find out what is costing the most is to use the debugger and randomly stop your code while it is running. Note not just the function currently being run, but all the functions on the "call stack" above it. After about 5 breaks, there should be one function (from anywhere in the call stack) that was showing in 3 or 4 of the samples--this is where to focus your attention.

Upvotes: 1

Related Questions