Minimise allocations for ModifierSum#739
Conversation
2351277 to
99490eb
Compare
|
As a general note, calling reserve explicitly is typically only an optimization if you can find a one-time upper bound on the possible growth and thereby call reserve once instead of allowing the vector to grow naturally. However, if you call reserve repeatedly you run the risk of performing much worse than the vector's normal exponential growth. The growth factor of the vector is designed so that adding elements is amortized O(1). Repeated calls to reserve that grow the vector only by some amount that we can place an upper bound on (as presumably happens here, since the total number of possible modifiers is bounded) makes the entire process (cycles of reserve + element additions) amortized O(n). In your particular case, a little back of the napkin math will show that just allocating space for every country to have every possible modifier times the number of land provinces is within the memory budget, so you can use that as the value for a single reservation and be very, very unlikely to ever need to grow the vectors. |
2eee5e5 to
0540214
Compare
8215f0e to
6c1f4ad
Compare
01af11a to
3435c92
Compare
3435c92 to
c9ba1d1
Compare
|
I'll add unit tests and then we can merge. |
55ec301 to
ed98ce9
Compare
1f173d0 to
44c0e3b
Compare
44c0e3b to
18d03f0
Compare
153f1c7 to
71daf85
Compare
71daf85 to
2b3344b
Compare
2b3344b to
dc042f6
Compare
CountryInstance::contribute_province_modifier_sumis called for each province (expect 10s-100s per country). Every call toModifierSum::add_modifier_sumcalledreserve_more, which is defined as:This resulted in repeated allocations, possibly reallocating the country's modifiersum for each controlled province.
Instead we now first sum the extra size for all provinces and then resize (not reserve!) once.
We use resize instead of reserve as it uses the underlying growth algorithm that typically reserves extra room, avoiding reallocating because of 1 extra element.
Resize creates empty elements which are later replaced. The ModifierSum keeps track of the count of valid elements and uses this for its
size().