Skip to content

Add dirty flag to Matrix2d/Matrix3d for faster isIdentity() checks #1378

@obiot

Description

@obiot

Summary

Matrix2d.isIdentity() and Matrix3d.isIdentity() compare every element against the identity matrix (9 and 16 comparisons respectively). These are called in the hot path — Renderable.preDraw() and updateBounds() check isIdentity() every frame for every renderable.

A dirty flag (_isIdentity) would reduce this to a single boolean check in the common case.

Proposed Change

Track identity state via a boolean flag:

identity() {
    // ... set values ...
    this._isIdentity = true;
}

translate() / rotate() / scale() / multiply() / etc {
    // ... do math ...
    this._isIdentity = false;
}

isIdentity() {
    return this._isIdentity;
}

Applies to

  • Matrix2d (src/math/matrix2d.ts) — 9 comparisons → 1 boolean
  • Matrix3d (src/math/matrix3d.ts) — 16 comparisons → 1 boolean

Caveats

  • val is a public Float32Array — users can write to it directly (e.g. matrix.val[12] = 100), bypassing the flag. This would make isIdentity() return a stale value.
  • Mitigation: document that direct val modification is unsupported, or call isIdentity() with a full check when the flag is dirty (not possible without tracking val mutations).
  • In practice, direct val access is rare and discouraged by the API docs.

Current optimization

As an interim measure, isIdentity() now checks translation components first (most commonly non-zero) to fail fast on non-identity matrices. This avoids the full comparison in the common case where the matrix has been translated.

References

  • Matrix3d.isIdentity(): src/math/matrix3d.ts:633
  • Matrix2d.isIdentity(): src/math/matrix2d.ts:405
  • Called from Renderable.preDraw(): src/renderable/renderable.js:746
  • Called from Renderable.updateBounds(): src/renderable/renderable.js:656

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions