0

I want to add some features to vectorLayer, but which one is more efficient?

1.addfeature()

for(let i =0;i< 5000;i++){
    let ft = new Feature({
        geometry: new Point(fromLonLat([lon, lat]))
    })
    vectorLayer.getSource().addFeature(ft)
}

2.addFeatures()

let fts = []
for(let i =0;i< 5000;i++){
    let ft = new Feature({
        geometry: new Point(fromLonLat([lon, lat]))
    })
    fts.push(ft)
}
vectorLayer.getSource().addFeatures(fts)

3.setSource()

let vectorSource = new vectorSource({})
for(let i =0;i< 5000;i++){
    let ft = new Feature({
        geometry: new Point(fromLonLat([lon, lat]))
    })
    vectorSource.addFeature(ft)
}
vectorLayer.setSource(vectorSource)

1 Answers1

1
const features = [];
for(let i = 0; i < 5000; ++i) {
    features.push(new Feature(new Point(fromLonLat([lon, lat]))));
}
vectorLayer.setSource(new VectorSource({
  features: features,
}));

If you are using a spatial index in the source (the default) it is most efficient to add all features together. https://github.com/mourner/rbush#bulk-inserting-data

Modifying a source that is already added to a layer will trigger a lot of events that can be avoided by simply creating a new source that is switched out after it has been initialized.

MoonE
  • 503
  • 3
  • 5