SS14 Standard Optimizations
The goal of the skill: quickly select the correct optimization for ECS code without degradation of readability and without outdated techniques :)
The main reference: the current behavior of the code. Documentation is an auxiliary layer.
When to use
- Optimize
Update, frequent event handlers, visual overlays, mass checks. - You do a code review and see frequent
TryComp/HasComp, LINQ in the hot-path, and unnecessary state components. - Looking for the source of lags/GC spikes in server/shared/client.
When not to use
- The code is rarely executed and is not in the hot path.
- Optimization complicates the code more than it provides benefits.
- No measurable symptom (frame time, GC, network delta size).
Reading order of resources
- Open
references/optimization-patterns.md- quick selection matrix. - Open
references/annotated-code-examples.md- live examples with comments. - Open
references/docs-reconciliation.md- comparison of docs and actual code.
Source of truth and boundaries of trust
- True - actual code of subsystems.
- Use Docs as a context for intentions and terms.
- If there is a conflict between docs and code, choose the code and explicitly record this in the reasoning.
- Don't rely on old pieces without checking for freshness and without the context of the changes.
Workflow optimization
- Find the hot-path and record the symptom.
- Choose the minimum technique from the cards below.
- Compare before/after: number of iterations, allocations, network deltas, behavior.
- Add a short explanation to your PR: “what was accelerated” and “why it’s safe.”
Optimization cards
1) Caching invariants and aggregates before hot-loop ⏱️
Pattern
- Compute expensive invariants before nested loops (shapes, set of angles, fast-path flags).
- Maintain aggregates incrementally (for example,
TargetCount,BurstShotsCount), rather than recalculating collections every tick. - Для частых проверок компонентов в
EntitySystemдополнительно использовать dependency
EntityQuery<T>.
Anti-pattern
- Call an expensive computation inside the inner loop.
- Each time, re-calculate “how much is already there/made”, going through the collections.
- Receive query/accessor in every hot-path call.
Code example
var itemShape = ItemSystem.GetItemShape(itemEnt); // One shape calculation before cycles.
var fastAngles = itemShape.Count == 1;
var angles = new ValueList<Angle>();
if (!fastAngles)
{
for (var angle = startAngle; angle <= Angle.FromDegrees(360 - startAngle); angle += Math.PI / 2f)
angles.Add(angle); // We precalculated the allowable angles once.
}
else
{
angles.Add(startAngle);
if (itemShape[0].Width != itemShape[0].Height)
angles.Add(startAngle + Angle.FromDegrees(90));
}
// In the inner loop we use only prepared data.
foreach (var angle in angles)
{
// Heavy placement/collision checking.
}
// Incremental aggregate instead of set recalculation:
if (gun.BurstActivated)
{
gun.BurstShotsCount += shots;
if (gun.BurstShotsCount >= gun.ShotsPerBurstModified)
{
gun.BurstActivated = false;
gun.BurstShotsCount = 0;
}
}
Why is it faster
- The number of repeated calculations in a deep loop is greatly reduced.
- The number of traversals of collections for the sake of one aggregate is reduced.
- The hot path works on already prepared data.
Limits of applicability
- The greatest effect is in algorithms with 2+ levels of cycles.
- For rare code, choose simplicity over micro-optimization.
2) Reduced allocations ♻️
Pattern
- Create working collections once as system/UI fields and clear them via
Clear(). - Pass existing lists/spans to the method instead of creating new ones.
- For temporary buffers in the hot-path, use a pool (
ArrayPool<T>) and a guaranteedReturn.
Anti-pattern
new List<T>()per frame/each call.- Copying large collections for one iteration.
- Ignoring the pool for repeated short-lived buffers.
Code example
private ValueList<EntityUid> _toRemove = new();
public override void Update(float frameTime)
{
var query = AllEntityQuery<ColorFlashEffectComponent>();
_toRemove.Clear(); // We will reuse without new allocation.
while (query.MoveNext(out var uid, out _))
{
if (_animation.HasRunningAnimation(uid, AnimationKey))
continue;
_toRemove.Add(uid);
}
foreach (var ent in _toRemove)
RemComp<ColorFlashEffectComponent>(ent);
}
Why is it faster
- The pressure on the GC is reduced.
- Jitter disappears due to frequent short-lived objects.
Limits of applicability
- Ensure collections are cleaned before reuse.
- The pool should always have a symmetrical return.
3) Refusal of LINQ in hot-path 🚫
Pattern
- In hot spots, use
for/foreachand explicit early exits. - Leave LINQ for rare/offline operations where compactness is more important.
Anti-pattern
Where/Select/Any/CountinUpdateand frequent handlers.- LINQ chains for simple filters in loops.
Code example
// ✅ Hot-path: a regular loop without unnecessary enumerators/closures.
for (var i = 0; i < entities.Count; i++)
{
var uid = entities[i];
if (!TryComp(uid, out MyComponent? comp))
continue;
Process(uid, comp);
}
// ❌ Don't do this in hot-path:
// entities.Where(HasComp<MyComponent>).Select(...).ToList();
Why is it faster
- Fewer intermediate objects and delegates.
- It is easier to control branches and early exits.
Limits of applicability
- Don't turn your code into "micro-optimized noise."
- If the area is not hot, readability may be more important.
4) Pattern Component + ActiveComponent 🔋
Pattern
- The base component stores the configuration.
- A separate
Active...Componentmarks “currently active”. Updatepasses only through active entities.
Anti-pattern
- One huge list of all entities +
if (!IsActive) continue. - Activity flags only inside the base component without a separate marker.
Code example
// Activating the timer: added an active marker.
EnsureComp<ActiveTimerTriggerComponent>(uid);
// Deactivation: the marker was removed, the entity disappeared from the target query.
RemComp<ActiveTimerTriggerComponent>(uid);
// Iterate over active timers only.
var query = EntityQueryEnumerator<ActiveTimerTriggerComponent, TimerTriggerComponent>();
Why is it faster
- The sample size is greatly reduced.
- Fewer active/inactive checks within the loop.
Limits of applicability
- We need discipline for state transitions (adding/removing a marker).
- The logic must remain consistent during shutdown/remove.
5) EntityQuery для `TryComp/HasComp/Resolve` 🔎
Pattern
- В
EntitySystemполучать часто используемыйEntityQuery<T>через[Dependency]. - Использовать
_query.TryComp/_query.HasComp/_query.Compвместо частых общих вызовов. - Перед добавлением поля проверять partial-файлы системы на query того же типа.
Anti-pattern
- Присваивать query через
GetEntityQuery<T>()вInitialize()новой системы. - Добавлять
[Dependency] EntityQuery<T>в команду, HTN-оператор, UI-контрол или оверлей. - Путать сохранённый
EntityQuery<T>с перечисляющими APIEntityQueryEnumerator<T...>(),
EntityQuery<T...>() и AllEntityQuery<T...>().
Code example
[Dependency] private EntityQuery<TagComponent> _tagQuery = default!;
public bool HasTag(EntityUid uid, ProtoId<TagPrototype> tag)
{
return _tagQuery.TryComp(uid, out var tagComp) &&
tagComp.Tags.Contains(tag);
}
Why is it faster
- A more direct path to component storage.
- Fewer redundant operations during mass checks.
Limits of applicability
- Выигрыш заметен при частых вызовах, а не в единичных местах.
- Ленивая регистрация query существует только в системной dependency-коллекции. Вне
EntitySystem использовать прямой доступ через IEntityManager, либо передавать query через
конструктор вручную создаваемого объекта.
6) Component order in `EntityQueryEnumerator()` 📉
Pattern
- Place the rarest component first.
- The second is less rare, and so on.
Anti-pattern
- Place the most massive component first and cross the huge set.
- Choose the order “as it came to mind.”
Code example
// ✅ Usually it’s better this way: Active* is less common.
var query = EntityQueryEnumerator<ActiveTimerTriggerComponent, TimerTriggerComponent>();
// ❌ Worse in most cases:
// var query = EntityQueryEnumerator<TimerTriggerComponent, ActiveTimerTriggerComponent>();
Why is it faster
- Fewer candidates when constructing the intersection of components.
- Lower cost of each
MoveNext.
Limits of applicability
- Assess the real cardinality in your subsystem.
- Check after changes to gameplay data/prototypes.
7) `ByRef record struct` for events ⚡
Pattern
- For frequent events, use
[ByRefEvent] public record struct .... - Pass such events through
ref.
Anti-pattern
- Use reference classes for high frequency local events unnecessarily.
- Forget
refwhen processing/calling a by-ref event.
Code example
[ByRefEvent] public record struct ChargedMachineActivatedEvent;
private void NotifyActivated(EntityUid uid)
{
var ev = new ChargedMachineActivatedEvent();
RaiseLocalEvent(uid, ref ev); // Transfer by reference.
}
Why is it faster
- Less copying of event data.
- Fewer unnecessary allocations in a frequent flow of events.
Limits of applicability
- For rare events, the gain may be negligible.
- Maintain a uniform signature style so as not to break the handler API.
8) `DirtyField` instead of `Dirty` for large network components 📡
Pattern
- For components with the set
AutoNetworkedFieldand field deltas enabled, only the changed fields are dirty. - Call
DirtyField(uid, comp, nameof(...))for point changes.
Anti-pattern
- Call
Dirty(uid, comp)for every small update of a large component. - Transmit the full state when one field has changed.
Code example
[AutoGenerateComponentState(fieldDeltas: true)]
public sealed partial class ProximityDetectorComponent : Component
{
[AutoNetworkedField] public TimeSpan NextUpdate;
[AutoNetworkedField] public float Distance;
}
component.NextUpdate += component.UpdateCooldown;
DirtyField(uid, component, nameof(ProximityDetectorComponent.NextUpdate));
Why is it faster
- Smaller size of network deltas.
- Lower load on serialization and sending state.
Limits of applicability
- If almost the entire state changes at once, the full
Dirtymay be normal.
9) Reducing busting and early exits 🚪
Pattern
- Put cheap filters first.
- Use early
return/continue. - Stop working immediately if the context is invalid.
Anti-pattern
- Calculate expensive things before simple checks.
- Deep nesting instead of direct filters.
Code example
while (query.MoveNext(out var uid, out var comp))
{
if (comp.NextUpdate > curTime)
continue; // Cheap filter first.
if (!_toggle.IsActivated(uid))
continue;
UpdateTarget((uid, comp));
}
Why is it faster
- Expensive is performed only for “reached” entities.
- The average cost of one iteration is reduced.
Limits of applicability
- Don't break readability: filters should be predictable.
10) Removing unnecessary components from an entity 🧹
Pattern
- After the state is completed, remove temporary/active components.
- Keep the entity minimal in terms of its current role.
Anti-pattern
- Leave temporary components “just in case.”
- Accumulate markers that are no longer involved in logic.
Code example
if (timer.NextTrigger <= curTime)
{
Trigger(uid, timer.User, timer.KeyOut);
RemComp<ActiveTimerTriggerComponent>(uid); // We remove the excess component immediately.
}
Why is it faster
- Fewer entities are included in future queries.
- Less unnecessary checks and network load.
Limits of applicability
- Removal should not break expected subscriptions/visual transitions.
Checklist before PR
- All changes are tied to a measurable hot-path.
- No LINQ in hot loop without conscious rationale.
- Query order is checked: from rare to massive.
- For large network components,
DirtyFieldis used where appropriate. - Temporary components are removed after the state is completed.
- The text and comments are not tied to specific code paths.
Rule for extending this skill
- Add only architecture-wide optimizations that are repeated in several subsystems.
- Narrow topics (for example, prediction-specific or atmos-specific) should be included in specialized skills.
- Add any new pattern along with an anti-pattern and a code example.