Tyler
Tyler

Reputation: 3813

Do instantiated objects of the same class add to memory (C#)?

I am currently working on a game for fun and had a question about c# performance.

I have two methods of doing the same task (below). I prefer Method 2, but I am worried about instantiating a class (PlayerMover) for each player (perhaps 100 players). Will it then keep 100 copies of PlayerMover in memory (one for each player)? In my examples below I only instantiate PlayerMover, but in reality it could be 10 different classes per player (PlayerSpawner, PlayerDespawner, etc.).

Method 1

class Player {
}
class Game {
    private PlayerMover _mover;
    private List<Player> _players;

    public Game() {
        _mover = new PlayerMover();
    }

    public void tick() {
        foreach (Player player in _players) {
            _mover.Move(player);
        }
    }
}

Method 2

class Player {
    private PlayerMover _mover;

    public Player() {
        _mover = new PlayerMover();
    }

    public void Move() {
        _mover.Move(this);
    }
}
class Game {
    private List<Player> _players;

    public void tick() {
        foreach (Player player in _players) {
            player.Move(player);
        }
    }
}

Upvotes: 1

Views: 412

Answers (2)

Christopher
Christopher

Reputation: 9804

I am currently working on a game for fun and had a question about c# performance.

Please read the Speed rant. However you do have a rare example where it might mater, if only due to the sheer scale.

I prefer Method 2, but I am worried about instantiating a class (PlayerMover) for each player (perhaps 100 players). Will it then keep 100 copies of PlayerMover in memory (one for each player)?

Yes, creating a new Instance will consume memory for each instance. And they can not be collected while the Player wrapping around them can not be collected. I could not find a definition of the class PlayerMover online. Some classes do not work properly if you do not keep a instance for each player. Some only work properly if you keep one instance around (Random is a good example). But I could find no information one way or the other, so I asume it is the bulk of "neutral" classes.

Unless there is some actuall technical need for one over the other, I would prefer wichever one is easier to read and code. For me readability always takes precendence over minor performance impacts.

Upvotes: 2

Benoit Bouckaert
Benoit Bouckaert

Reputation: 65

In the first way, only one PlayerMover will be instanciated.

In the second one, none will be instanciated, as you don't create instances of your Player class. But if you do, there will be as much PlayerMover as Player instances.

Upvotes: 0

Related Questions