Search code examples
c#arraysinitializationjagged-arrays

Is there any way to speed up array initialization?


I have a function that stores values inside some arrays. Every time the function is called, the arrays have to be cleared before putting items in them.

public static void UpdateAttackedPieces()
    {
        attackedSquares = new List<int>[2][];

        for (int color = 0; color < 2; color++) attackedSquares[color] = new List<int>[64];

        for (int color = 0; color < 2; color++) for (int i = 0; i < 64; i++) attackedSquares[color][i] = new List<int>();

        checkAttackersRays = new List<int>[2][];

        for (int color = 0; color < 2; color++) checkAttackersRays[color] = new List<int>[64];

        for (int color = 0; color < 2; color++) for (int i = 0; i < 64; i++) checkAttackersRays[color][i] = new List<int>();

        // Update arrays
    }

(It is a chess program and the function is for updating pieces under attack).

attackedSquares is an array (one per color) of the 64 squares on the board which holds information about its attackers (so attackedSquares[0][4][2] is the third attacker on the fifth square for white, for example)

I've done some testing and about 35% of the time it takes to run the function is spent initializing the jagged arrays. Is there a faster way to do this?


Solution

  • Thanks to @Matthey Watson's comment, I was able to bring the time down from 6.5 seconds to less than 1 second with this change in the code:

    public static void UpdateAttackedPieces()
        {
            for (int color = 0; color < 2; color++) for (int i = 0; i < 64; i++) attackedSquares[color][i].Clear();
    
            for (int color = 0; color < 2; color++) for (int i = 0; i < 64; i++) checkAttackersRays[color][i].Clear();
    
            // Update arrays
        }