[Perf] MVTLayer: index binary tiles once for picking and highlighting instead of scanning every vertex per hover and per frame
Maintainers usually reply within 1 day
Nobody has claimed this yet.
Assessment
- Difficulty
- 5/5
- Estimated time
- Over a week
- Newbie friendliness
- 35/100
- Issue type
- Feature
- Clarity
- Mostly clear
- Activity status
- Active
- Tech stack
- javascript, typescript
- Domain
- frontend, performance
Research direction
Start with modules/geo-layers/src/mvt-layer/mvt-layer.ts, then read find-index-binary.ts and coordinate-transform.ts; the issue describes three separate hot paths for binary feature picking, highlighting, and WGS84 coordinate access. Check the existing tile cache patterns and relevant MVT layer tests before choosing an approach. Done means indexing or memoizing the repeated work while preserving rendered output and the existing API, with tests covering each affected path.
Written by the indexing model from the issue text.
Description
Target Use Case
Interactive vector-tile maps with pickable: true, autoHighlight, uniqueIdProperty / highlightedFeatureId, or getRenderedFeatures().
With the default binary: true, three hot paths do work that grows with the vertex count of every tile and they run per pointer move or per rendered frame:
- Hover picking: converting the hovered feature to GeoJSON scans the tile's vertex arrays from the start: 1.65 ms per pick on a normal tile, 16.5 ms on a heavy one. Hovering inside the same feature repeats the scan on every pointer move.
- Highlighting: while any feature is hovered or
highlightedFeatureIdis set, every render scans every cached tile for the feature id. Renders include every pan/zoom frame. With a numericuniqueIdProperty, that's about 115 ms per frame with 100 cached normal tiles. - WGS84 coordinates on picked features:
geometry.coordinatesis a getter that re-projects the whole geometry, and returns a new array, on every read.
All proposals below are internal caches, so no changes to rendered output and no API.
References are against master @ 64cf9d4 (Nov 18, 2026). loaders.gl references are to v5.0.0-beta.12.
Proposal
1. Hover pick: index each binary tile by globalFeatureId instead of scanning
Where
mvt-layer.tsL360–377: in binary mode,getPickingInfocallsconvertBinaryFeatureCollectionToGeojson(data, {globalFeatureId: info.index})for every pick.- loaders.gl
convert-binary-features-to-geojson.tsL49–75:getSingleFeaturewalksfeatureIdsvertex by vertex through points, then lines, then polygons, until it reaches the feature.
What happens
- each hover that hits a feature costs a scan up to that feature's vertices, plus parsing the feature.
- nothing is cached, moving the pointer within the same polygon repeats the full scan and returns a new object each time, meaning
info.objectidentity is unstable even for the same feature. - polygons come last in scan order, so they are the slowest to resolve.
Effect. Measured on one tile, picking a polygon:
| mid polygon | last polygon | indexed lookup | index build, once per tile | |
|---|---|---|---|---|
| Normal tile (198k vertices) | 0.96 ms | 1.65 ms | ~9 ns | 2.2 ms |
| Heavy tile (1.98M vertices) | 10.8 ms | 16.5 ms | ~8 ns | 24 ms |
This is per pointer move, on the main thread. It is in addition to the GPU pick, and to the highlight work in #2 whenever the hovered id changes.
getRenderedFeatures(), L434–453 goes through the same getPickingInfo for every picked object, so its cost is roughly (objects × the scan). As an extrapolation: 1000 rendered polygons at ~1 ms each is about 1 s.
Proposal
- On the first pick per tile, build a
MapfromglobalFeatureIdto{type, start, end}(vertex range) in one pass. Store it on the tile, the same wayfind-index-binary.tsalready caches__layers/__idson the tile data. - Parse only that range. This could be a deck-side helper, or a loaders.gl option to pass a precomputed range or index (I can file this one upstream too).
- Additionally, memoize the last
(tile, globalFeatureId) → feature. Hovering within one feature then returns the same object, which helpsonHoverconsumers that compare identity.
The index costs about as much as one or two scans, so it pays for itself by the second pick on a tile.
2. Highlighting: per-tile id index, instead of scanning every cached tile on every render
Where
mvt-layer.tsL379–421:getSubLayerPropsByTile→getHighlightedObjectIndex→findIndexBinary(...)for each tile.tile-layer.tsL445–476:renderLayers()callsgetSubLayerPropsByTile(tile)for every tile intileset.tiles. That is the whole cache (tileset-2d.tsL284–286), not just the visible tiles. By default the cache holds 5× the selected tiles (DEFAULT_CACHE_SCALE, L59).tile-layer.tsL246–248:shouldUpdateStatereturnschangeFlags.somethingChanged, which includesviewportChanged. SorenderLayers()re-runs on every pan/zoom frame (layer.tsL911–922,composite-layer.tsL292–304).find-index-binary.tsL60–83. With a numericuniqueIdProperty, the id lives innumericProps, which are stored per vertex. L62–67 then runnumericProps[prop].value.findIndex(...)over every vertex of the tile, checkingfeatureIds[i]against the layer range on each one. A string id scanspropertiesper feature instead (L68–74).
What happens. Whenever hoveredFeatureId or highlightedFeatureId is set, every render scans every cached tile for the id. Most tiles don't contain the feature, so most scans run to the end. Nothing caches the result. The scan repeats on every animation frame while panning or zooming with a highlight active, and again whenever the hovered feature changes.
Effect. Measured as one renderLayers() worth of findIndexBinary calls, searching for a feature present in one tile:
numeric uniqueIdProperty (master) |
string uniqueIdProperty (master) |
per-tile index (warm) | |
|---|---|---|---|
| 100 cached normal tiles | 115 ms | 3.0 ms | 10 µs |
| 10 cached heavy tiles | 114 ms | 5.3 ms | 0.9 µs |
With numeric ids, which are common (e.g. OSM ids), this alone exceeds a frame budget many times over during interaction.
Proposal
- Build a per-tile
Mapfrom(layerName, idValue)toglobalFeatureIdlazily, in one pass over the first vertex of each feature. Store it on the tile data next to the existing__layers/__idscaches, keyed byuniqueIdProperty. - Optionally cache the last
(featureId, layerName) → indexper tile, so re-renders with an unchanged highlight are O(1) even before the index exists. binary: falsetiles take thedata.findIndexbranch (L401–407) instead, then hit the GeoJsonLayer point-highlightfindIndex(filed separately). The same index applies there.
3. Memoize WGS84 coordinates on picked and dataInWGS84 features
Where
mvt-layer.tsL515–532:transformTileCoordsToWGS84definesgeometry.coordinatesas a getter that callstransform(object.geometry, bbox)on every access.coordinate-transform.tsL49–58:transformrecomputes the bbox corners withlngLatToWorldand allocates new nested coordinate arrays for the whole geometry.- Both
info.objectfromgetPickingInfo(L369–374) and every feature oftile.dataInWGS84(L483–485) use this getter. ThedataInWGS84array is cached, but each feature's coordinates are not.
What happens
- Each read of
feature.geometry.coordinatesre-projects the whole geometry. That includes reads by turf, by tooltip code, and by React re-renders. feature.geometry.coordinates !== feature.geometry.coordinates. That breaks identity-based memoization, and any mutation of the returned array is silently lost.
Effect. Reading a small picked polygon's coordinates 10×: 27 µs vs 2.9 µs if memoized. The cost scales with vertex count, and with how many features consumers touch via dataInWGS84.
Proposal. Compute on first access, then replace the getter with the value (Object.defineProperty(geometry, 'coordinates', {value, writable: true})), keeping it lazy. This is about a two-line change.
Measurements
- Fixtures. Synthetic MVT-like tiles converted with loaders.gl
geojsonToBinary({triangulate: true}), the same binary layoutMVTLoaderemits. Polygons with holes and MultiPolygons come first, then lines and points. Each feature has a numericosm_id(stored innumericProps), a stringgid(inproperties) and alayerName.- Normal tile: 8k features, 198k vertices.
- Heavy tile: 80k features, 1.98M vertices.
Reference diff (authored with Opus 5.5):
diff --git a/modules/geo-layers/src/mvt-layer/binary-feature-index.ts b/modules/geo-layers/src/mvt-layer/binary-feature-index.ts
new file mode 100644
index 0000000..c3ab564
--- /dev/null
+++ b/modules/geo-layers/src/mvt-layer/binary-feature-index.ts
@@ -0,0 +1,85 @@
+// deck.gl
+// SPDX-License-Identifier: MIT
+// Copyright (c) vis.gl contributors
+
+import {
+ convertBinaryFeatureCollectionToGeojson,
+ convertBinaryGeometryToGeometry
+} from '@loaders.gl/core/geoarrow';
+import type {BinaryFeatureCollection} from '@loaders.gl/core/schema';
+import type {Feature} from 'geojson';
+
+const GEOMETRY_TYPES = {points: 'Point', lines: 'LineString', polygons: 'Polygon'} as const;
+type GeometryKey = keyof typeof GEOMETRY_TYPES;
+
+/** Vertex range of one feature inside a geometry type's arrays. */
+type FeatureRange = {key: GeometryKey; start: number; end: number};
+
+/** Picking caches stored on the tile data, like the `__layers` / `__ids` caches in find-index-binary. */
+type IndexedBinaryTile = BinaryFeatureCollection & {
+ __featureRanges?: Map<number, FeatureRange>;
+ __lastPicked?: {globalFeatureId: number; feature: Feature};
+};
+
+/**
+ * Builds a globalFeatureId -> vertex range index in one pass over the tile.
+ * A feature's vertices are contiguous within its geometry type, as loaders.gl writes them.
+ */
+function getFeatureRanges(data: IndexedBinaryTile): Map<number, FeatureRange> {
+ if (!data.__featureRanges) {
+ const ranges = new Map<number, FeatureRange>();
+ for (const key of Object.keys(GEOMETRY_TYPES) as GeometryKey[]) {
+ const globalFeatureIds = data[key]?.globalFeatureIds.value;
+ if (!globalFeatureIds) {
+ continue; // eslint-disable-line no-continue
+ }
+ for (let i = 0; i < globalFeatureIds.length; i++) {
+ const range = ranges.get(globalFeatureIds[i]);
+ if (range) {
+ range.end = i + 1;
+ } else {
+ ranges.set(globalFeatureIds[i], {key, start: i, end: i + 1});
+ }
+ }
+ }
+ data.__featureRanges = ranges;
+ }
+ return data.__featureRanges;
+}
+
+/**
+ * Returns the GeoJSON feature for a picked global feature id.
+ * Parses only that feature's vertex range instead of scanning the tile, and returns the same
+ * object for repeated picks of the same feature (e.g. moving the pointer within one polygon).
+ */
+export function getBinaryFeature(data: BinaryFeatureCollection, globalFeatureId: number): Feature {
+ const tile = data as IndexedBinaryTile;
+ const lastPicked = tile.__lastPicked;
+ if (lastPicked?.globalFeatureId === globalFeatureId) {
+ return lastPicked.feature;
+ }
+
+ const range = getFeatureRanges(tile).get(globalFeatureId);
+ if (!range) {
+ // Unexpected layout: keep the previous behavior, including its error for unknown ids.
+ return convertBinaryFeatureCollectionToGeojson(data, {globalFeatureId}) as Feature;
+ }
+
+ const {key, start, end} = range;
+ const binary = tile[key] as any;
+ const featureIndex = binary.featureIds.value[start];
+ // Same shape as loaders.gl's parseFeature: geometry, merged properties, then fields.
+ const properties = {...binary.properties[featureIndex]};
+ for (const prop in binary.numericProps) {
+ properties[prop] = binary.numericProps[prop].value[start];
+ }
+ const feature = {
+ type: 'Feature',
+ geometry: convertBinaryGeometryToGeometry({...binary, type: GEOMETRY_TYPES[key]}, start, end),
+ properties,
+ ...binary.fields?.[featureIndex]
+ } as Feature;
+
+ tile.__lastPicked = {globalFeatureId, feature};
+ return feature;
+}
diff --git a/modules/geo-layers/src/mvt-layer/find-index-binary.ts b/modules/geo-layers/src/mvt-layer/find-index-binary.ts
index f4634eb..c372189 100644
--- a/modules/geo-layers/src/mvt-layer/find-index-binary.ts
+++ b/modules/geo-layers/src/mvt-layer/find-index-binary.ts
@@ -33,111 +33,79 @@ export default function findIndexBinary(
return -1;
}
+/** Key for "any layer" lookups; MVT layer names are non-empty strings. */
+const ANY_LAYER = '';
+
+/** layerName (or ANY_LAYER) -> feature id -> global feature id of the first matching feature */
+type IdIndex = Map<string, Map<unknown, number>>;
+
+type IndexedGeometry = FeatureTypes & {
+ __idIndexes?: Record<string, IdIndex>;
+};
+
function findIndexByType(
geomData: FeatureTypes,
uniqueIdProperty: string,
featureId: string | number,
layerName: string | null
): number {
- const featureIds = geomData.featureIds.value;
-
- if (!featureIds.length) {
- return -1;
- }
+ const index = getIdIndex(geomData as IndexedGeometry, uniqueIdProperty);
+ return index.get(layerName || ANY_LAYER)?.get(featureId) ?? -1;
+}
- let startFeatureIndex = 0;
- let endFeatureIndex = featureIds[featureIds.length - 1] + 1;
- if (layerName) {
- const layerRange = getLayerRange(geomData, layerName);
- if (layerRange) {
- startFeatureIndex = layerRange[0];
- endFeatureIndex = layerRange[1] + 1;
- } else {
- return -1;
- }
+/**
+ * Builds, once per geometry type and uniqueIdProperty, a lookup from feature id to global
+ * feature id, instead of scanning every vertex (numericProps) or feature on each call.
+ * Keeps the previous semantics: the first matching feature wins, numericProps take precedence
+ * over properties, and an empty uniqueIdProperty matches `fields[i].id`.
+ */
+function getIdIndex(geomData: IndexedGeometry, uniqueIdProperty: string): IdIndex {
+ if (!geomData.__idIndexes) {
+ geomData.__idIndexes = {};
}
-
- // Look for the uniqueIdProperty
- let featureIndex = -1;
- if (uniqueIdProperty in geomData.numericProps) {
- const vertexIndex = geomData.numericProps[uniqueIdProperty].value.findIndex(
- (x, i) =>
- x === featureId && featureIds[i] >= startFeatureIndex && featureIds[i] < endFeatureIndex
- );
- return vertexIndex >= 0 ? geomData.globalFeatureIds.value[vertexIndex] : -1;
- } else if (uniqueIdProperty) {
- featureIndex = findIndex(
- geomData.properties,
- elem => elem[uniqueIdProperty] === featureId,
- startFeatureIndex,
- endFeatureIndex
- );
- } else if (geomData.fields) {
- featureIndex = findIndex(
- geomData.fields,
- (elem: any) => elem.id === featureId,
- startFeatureIndex,
- endFeatureIndex
- );
+ const cache = geomData.__idIndexes;
+ let index = cache[uniqueIdProperty];
+ if (index) {
+ return index;
}
- return featureIndex >= 0 ? getGlobalFeatureId(geomData, featureIndex) : -1;
-}
-type LayerRange = [firstFeatureIndex: number, lastFeatureIndex: number];
+ index = new Map([[ANY_LAYER, new Map()]]);
+ const featureIds = geomData.featureIds.value;
+ const globalFeatureIds = geomData.globalFeatureIds.value;
+ const numericValues =
+ uniqueIdProperty in geomData.numericProps
+ ? geomData.numericProps[uniqueIdProperty].value
+ : null;
-// Returns [firstFeatureIndex, lastFeatureIndex]
-// MVTLoader parses tiles layer-by-layer, so each layer is a continuous range
-function getLayerRange(
- geomData: FeatureTypes & {
- __layers?: Record<string, LayerRange>;
- },
- layerName: string
-): LayerRange | undefined {
- if (!geomData.__layers) {
- // Cache a map from properties.layerName to index ranges
- const layerNames: Record<string, LayerRange> = {};
- const {properties} = geomData;
- for (let i = 0; i < properties.length; i++) {
- const {layerName: key} = properties[i];
- if (!key) {
- // ignore
- } else if (layerNames[key]) {
- layerNames[key][1] = i;
- } else {
- layerNames[key] = [i, i];
- }
+ for (let i = 0; i < featureIds.length; i++) {
+ // Visit each feature once, at its first vertex.
+ if (i > 0 && featureIds[i] === featureIds[i - 1]) {
+ continue; // eslint-disable-line no-continue
}
- geomData.__layers = layerNames;
- }
- return geomData.__layers[layerName];
-}
-
-// Returns global feature id
-function getGlobalFeatureId(geomData, featureIndex: number) {
- if (!geomData.__ids) {
- // Cache a map from featureId to globalFeatureId
- const result: string[] = [];
- const featureIds = geomData.featureIds.value;
- const globalFeatureIds = geomData.globalFeatureIds.value;
- for (let i = 0; i < featureIds.length; i++) {
- result[featureIds[i]] = globalFeatureIds[i];
+ const featureIndex = featureIds[i];
+ const properties = geomData.properties[featureIndex];
+ let id: unknown;
+ if (numericValues) {
+ id = numericValues[i];
+ } else if (uniqueIdProperty) {
+ id = properties?.[uniqueIdProperty];
+ } else {
+ id = (geomData as any).fields?.[featureIndex]?.id;
}
- geomData.__ids = result;
- }
- return geomData.__ids[featureIndex];
-}
-// Like array.findIndex, but only search within a range
-function findIndex<T>(
- array: T[],
- predicate: (v: T, index: number) => boolean,
- startIndex: number,
- endIndex: number
-): number {
- for (let i = startIndex; i < endIndex; i++) {
- if (predicate(array[i], i)) {
- return i;
+ const layerName = properties?.layerName;
+ for (const key of layerName ? [ANY_LAYER, layerName] : [ANY_LAYER]) {
+ let ids = index.get(key);
+ if (!ids) {
+ ids = new Map();
+ index.set(key, ids);
+ }
+ if (!ids.has(id)) {
+ ids.set(id, globalFeatureIds[i]);
+ }
}
}
- return -1;
+
+ cache[uniqueIdProperty] = index;
+ return index;
}
diff --git a/modules/geo-layers/src/mvt-layer/mvt-layer.ts b/modules/geo-layers/src/mvt-layer/mvt-layer.ts
index e6a3ae2..77e1843 100644
--- a/modules/geo-layers/src/mvt-layer/mvt-layer.ts
+++ b/modules/geo-layers/src/mvt-layer/mvt-layer.ts
@@ -25,6 +25,7 @@ import type {Feature, Geometry} from 'geojson';
import {transform} from './coordinate-transform';
import findIndexBinary from './find-index-binary';
+import {getBinaryFeature} from './binary-feature-index';
import TileLayer, {TileLayerPickingInfo, TileLayerProps} from '../tile-layer/tile-layer';
@@ -108,6 +109,9 @@ export type _MVTLayerProps<FeaturePropertiesT> = Omit<
type ContentWGS84Cache = {_contentWGS84?: Feature[]};
+/** WGS84 view of a tile-local feature, so repeated picks of one feature return one object. */
+const wgs84Features = new WeakMap<Feature, Feature>();
+
/** Render data formatted as [Mapbox Vector Tiles](https://docs.mapbox.com/vector-tiles/specification/). */
/**
* Compatibility MVT layer retaining binary data, TileJSON, and rendered-feature APIs.
@@ -362,15 +366,20 @@ export default class MVTLayer<
if (this.state.binary && info.index !== -1) {
const {data} = params.sourceLayer!.props;
- info.object = convertBinaryFeatureCollectionToGeojson(data as BinaryFeatureCollection, {
- globalFeatureId: info.index
- }) as Feature;
+ // Indexed per tile: parses only the picked feature's vertex range.
+ info.object = getBinaryFeature(data as BinaryFeatureCollection, info.index);
}
if (info.object && !this._isWGS84()) {
- info.object = transformTileCoordsToWGS84(
- info.object,
- info.tile!.bbox as GeoBoundingBox // eslint-disable-line
- );
+ const tileFeature = info.object;
+ let feature = wgs84Features.get(tileFeature);
+ if (!feature) {
+ feature = transformTileCoordsToWGS84(
+ tileFeature,
+ info.tile!.bbox as GeoBoundingBox // eslint-disable-line
+ );
+ wgs84Features.set(tileFeature, feature);
+ }
+ info.object = feature;
}
return info;
@@ -520,11 +529,14 @@ function transformTileCoordsToWGS84(object: Feature, bbox: GeoBoundingBox): Feat
}
};
+ // Transform lazily, once: later reads return the same array instead of re-projecting.
// eslint-disable-next-line accessor-pairs
Object.defineProperty(feature.geometry, 'coordinates', {
- get: () => {
- const wgs84Geom = transform(object.geometry, bbox);
- return wgs84Geom.coordinates;
+ configurable: true,
+ get() {
+ const {coordinates} = transform(object.geometry, bbox);
+ Object.defineProperty(this, 'coordinates', {value: coordinates, writable: true});
+ return coordinates;
}
});
- Dominant language
- TypeScript
- Stars
- 14.8k
- Forks
- 2.3k
- Avg merge
- 1d 9h
- Merged PRs (30d)
- 230
Getting set up
- No Dockerfile or Docker Compose file
- Has a pull request template
- Read the contributing guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from visgl/deck.gl
-
[Bug] Tile3DLayer selects no tiles until the camera moves when tileset.json loads right after a layer updatePossibly taken @lee3Q claimed this 3 days ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
Maintainers usually reply within 1 day
-
[Bug] SplitterWidget calls onDragStart on drag end; Deck._getViews writes into the app's views arrayPossibly taken @04jennet-coder claimed this 20 days ago. Openbug
Difficulty 2/5 1-3 hours Newbie friendliness 78/100
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 77/100
Maintainers usually reply within 1 day
-
[Bug] WMSLayer positions EPSG:4326 images as CARTESIANPossibly taken @athomct claimed this 3 days ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 85/100
Maintainers usually reply within 1 day
-
[Bug] MapLibreOverlay under React StrictMode: 'WebGL context already attached to device' because the attach path omits _reuseDevicesPossibly taken @jsve claimed this 84 days ago. Open
Difficulty 2/5 1-3 hours Newbie friendliness 85/100
visgl/deck.gl#10681 · 1 comment · 1 reaction ·
Maintainers usually reply within 1 day
Similar issues
-
accessibility area:ci ci-test level:low priority:high type:test
Difficulty 2/5 1-3 hours Newbie friendliness 71/100
skytuhua-org/Gen-V1#3132 · 1 comment ·
Maintainers usually reply within 1 day
-
Difficulty 2/5 1-3 hours Newbie friendliness 76/100
drmrd/vernacular#1238 ·
Maintainers usually reply within 1 day
-
question
Difficulty 2/5 1-3 hours Newbie friendliness 65/100
-
enhancement migration-prioritized
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
Hudson-Pufferfish/local-party-console#136 ·
Maintainers usually reply within 1 day
-
priority:medium
Difficulty 2/5 1-3 hours Newbie friendliness 75/100
Maintainers usually reply within 1 day