C# For vs Foreach

I was experiencing significant frame dropping while working on my current game project “County Farm”. While tilling the soil the game would start out smooth render each frame correctly. However, the more dirt tiles present it got slower and slower. The frames went from 700 down to a crawling 22 during this quick action.

My game tiles are stored in a List<> rather than an array and I know for raw computing power that arrays are faster. However, lists offer some really nice helper methods and just making it easier to deal with dynamic sets of data.

I started researching the best way to iterate over this List<> data. I’ve always leaned towards foreach for readability. The code looks nicer, its easier to follow, and it generally cleaner. However, after doing some testing I found that the for loop is nearly 2.5x faster than foreach on the same data set.

Here is the function I was working on, as you can see its pretty simple. This code has an entire posts dedicated to it if you’re interested in understanding how bitmasking works.

    /// <summary>
    /// Evaluate all gameObject tiles in a given array
    /// </summary>
    /// <param name="goList">array of gameObjects to be evaluated</param>
    public void EvaluateAllTiles(GameObject[] goList)
        //Iterate over each gameObject
        for (int i = 0; i < goList.Length; i++)
            if (goList[i].tag == "Soil")
                int runningTotal = 0;
                Tile tile = goList[i].GetComponent<Tile>();
                //Call our evaluate tile against the current gameObject tile
                runningTotal = EvaluateTile(goList[i].transform.position);
                //If the tileType is soil, use the TillSoil method
                //provide the running total to change the sprite

Leave a Reply