Leaflet.markercluster
Leaflet.markercluster copied to clipboard
Improve performance of addLayers by preallocating array
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.
thanks for maintaining this project! Is there any chance someone could take a look at this?
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.
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 :)
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 - 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