Leaflet.markercluster icon indicating copy to clipboard operation
Leaflet.markercluster copied to clipboard

Improve performance of addLayers by preallocating array

Open pmarrapese opened this issue 5 years ago • 6 comments

Presently, addLayers pushes a new element onto MarkerClusterGroup._needsClustering for each qualifying element in layersArray. This is inefficient because the array is being resized upon every iteration, which is a very expensive operation. This problem really starts to become evident when adding a large number of markers.

This pull request resolves this problem by preallocating the array instead of repeatedly resizing it. Using a dataset of 120,866 markers, this simple fix reduced my average addLayers call time from 8.9s to 0.5s.

pmarrapese avatar Apr 06 '20 02:04 pmarrapese

thanks for maintaining this project! Is there any chance someone could take a look at this?

goapunk avatar Oct 05 '22 11:10 goapunk

Made a minor but important update to this: this._needsClustering.push was resulting in a "Maximum call stack size exceeded" exception on some mobile browsers (Safari on iPhone) when working with very large sets of markers. this._needsClustering.concat prevents this from occurring.

pmarrapese avatar Oct 26 '22 22:10 pmarrapese

I was half-way into building a cusom static clustered grid to solve this.

6.5s --> 1.2s with this solution

@pmarrapese this is fantastic, please pull this :)

nconnector avatar Nov 24 '22 06:11 nconnector

Hi @pmarrapese , this seems like an important perf improvement and def would like to merge it. any minimal examples that could reproduce the efficiency improvements on jsfiddle?

ykzeng avatar May 22 '23 21:05 ykzeng

@ykzeng - Sorry for the wait here! Finally had some time to do a demo. Open the console for logging. Tested on Chrome 114.0.5735.199 / Windows 10 (64-bit).

My changes; using leaflet.markercluster-src.js built from https://github.com/pmarrapese/Leaflet.markercluster/commit/f43d89c61da759afbdaeee93e288b09eb076235e

  • URL: https://jsfiddle.net/pmarrapese/vh8zc0t7/
  • Adding 205,705 layers takes ~0.13s

Without my changes; leaflet.markercluster-src.js built from bd2794c35831612a86f63766c26d94f809de7abc

  • URL: https://jsfiddle.net/pmarrapese/tyo3hbnf/
  • Adding 205,705 layers takes ~21.15s

pmarrapese avatar Jul 16 '23 22:07 pmarrapese