Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

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.

    /// 
    /// Evaluate all gameObject tiles in a given array
    /// 
    /// array of gameObjects to be evaluated
    public void EvaluateAllTiles(GameObject[] goList)
    {
        //Iterate over each gameObject
        for (int i = 0; i ();
                //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
                tile.TillSoil(runningTotal);
            }
        }
    }


This post first appeared on Diaonic - Coding, Tutorials, And Life Hacks, please read the originial post: here

Share the post

C# For vs Foreach

×

Subscribe to Diaonic - Coding, Tutorials, And Life Hacks

Get updates delivered right to your inbox!

Thank you for your subscription

×