Are components contiguous in memory?

One of the benefits of using a component/entity driven paradigm is that the components are contiguous in memory. That’s cache friendly and well suited to multi-threaded applications. Does unity take this approach? Could you easily get a list of all components of type T in a scene and have systems that operate on these in unity?

So you can get a list of all GameObjects in the scene using components of type T by calling GameObject.FindObjectOfType(typeof(T)) as T but I’m not sure that’s done in the same method you are referring to as this method is very slow for obvious reasons.

Unity components are allocated by the Mono runtime and garbage collected, thus, unless the Unity developers have heavily modified Mono’s allocation behavior, you’d get this behavior:

  • Memory is dealt out sequentially. Allocated objects will be placed in memory one after another ordered by creation time (but not type).
  • At any time, a compaction can occur which juggles objects around in physical memory randomly to close gaps where freed objects were located.
  • On top of that, your OS runs the CPU in protected mode, so each 4K page can (and likely will) be at a completely different location in physical memory.

Cache coherency is an interesting topic in CPU-side particle systems and anything dealing with mass data, but from my point of view Unity components are high-level enough (you only have a few hundred active per scene typically) that I’d focus solely on convenience and algorithmic efficiency.

Now if you have a specific problem you’re thinking about, maybe Unity already offers an efficient solution other than enumerating all components of a type.

Many such queries can be supported by the highly optimized code in PhysX. For example, if your space combat game’s targeting system needs a list of the closest X enemies, you can put a sphere collider on the ship with a component that keeps a list of in-range enemies via OnTriggerEnter() and OnTriggerLeave(), letting PhysX handle spatial indexing and object island building.