Back to all reviewers

Reserve container capacity early

maplibre/maplibre-native
Based on 3 comments
Other

When using containers like `unordered_map`, `unordered_set`, or vectors in performance-critical code, always pre-allocate space by calling `reserve()` before adding elements. This prevents expensive rehashing or reallocation operations during insertion, which can cause significant performance degradation, especially in rendering loops or frequently called...

Performance Optimization Other

Reviewer Prompt

When using containers like unordered_map, unordered_set, or vectors in performance-critical code, always pre-allocate space by calling reserve() before adding elements. This prevents expensive rehashing or reallocation operations during insertion, which can cause significant performance degradation, especially in rendering loops or frequently called functions.

For string-heavy lookups and comparisons, consider using specialized containers like StringIndexer with unordered_set<StringIdentity> instead of storing and comparing raw strings directly.

Example:

// Suboptimal: May cause multiple reallocations
std::unordered_map<TextureID, TextureDesc> textureMap;
// Add many elements...

// Better: Pre-allocate expected capacity
std::unordered_map<TextureID, TextureDesc> textureMap;
textureMap.reserve(expectedCount); // Prevent rehashing during insertion
// Add many elements...

// Even better for string comparisons in hot paths:
std::unordered_set<StringIdentity> propertiesAsUniforms;
propertiesAsUniforms.reserve(expectedPropertyCount);
// This optimization can help with performance in methods called per frame

This simple practice can significantly reduce memory allocation overhead, especially in data structures accessed in rendering loops or hot paths in your graphics code.

3
Comments Analyzed
Other
Primary Language
Performance Optimization
Category

Source Discussions