Showing the how without showing the why is probably not helpful IMO. Why is important here.
Using ECS is somewhat like treating your game state like a normalized database. It lets you perform operations on all the items of a certain type at once.
Say in my game I need to recenter my origin on a regular basis. In an open world game, you want to make sure that players don't start to see errors caused by floating point arithmetic, and the further away their position gets from 0, the worse this gets. To fix it, one option is to transform all positions by the same amount to keep the player's absolute position near (0, 0, 0).
To do this in the hierarchy style, the code might look like this: (Using JS because I was writing it today so that's where my brain is)
var gameObjects = world.getAllGameObjects();
var offset = [-1000, 0, 500]; // Pretend it's a real vector
// Iterate through every single object in the game
// (Not using foreach or filtering in either example, sue me)
for(var gameObject in gameObjects) {
// Branch on every game object just to see if it's positioned in the world
if(gameObject.position !== null) {
// Do what I really wanted to do
gameObject.position.add(offset);
}
}
Meanwhile, the ECS version would look more like this:
// This can vary greatly based on implementation
// I'm going to go with an option that reads easily
// This should just give back the list of components, which we'll say is an array.
// Lookup time in this fictional system is the cost of a dictionary lookup.
var positions = world.getComponents('position');
var offset = [-1000, 0, 500]; // Pretend it's a real vector
// Iterate through only the things we care about
// Not using map here, sue me
for(var position in positions) {
// Do what I really wanted to do
position.add(offset);
}
Not only is the second example shorter, but it's also doing a
lot less work. We're adding a vector to an array of vectors. No branching, no touching objects we don't care about, nothing extra.
Many ECS systems will allow you to filter down to the set of entities that have two or more components at the same time. Obviously more expensive, but still not as wasteful as checking every object or adding an update function to run every tick on every relevant entity.
The above code was written just before bedtime and not against a real ECS library or OO hierarchy, so please forgive any obvious errors.