need help stopping these lag spikes when my list iterates

Hey guys, I’m having trouble with something. I’m making a huge tile based procedural world, and using object pooling to keep the performance up. Now it works pretty well, but I have a script that iterates through every point and checks to see if it should place a tile at that spot. Here is what it looks like right now:

    IEnumerator CheckActivation()
    {

        
        if (activatorItems.Count > 0)
        {
            for(int i=0;i<activatorItems.Count;i++)
            {

                if (Vector3.Distance(plrtransform.position, activatorItems*.itemPos) < distanceFromPlayer)*

{

if (activatorItems*.itemName.Contains(“grasstile”))*
{
objectPooler.Instance.SpawnFromPool(“GrassTile”, activatorItems*.itemPos, Quaternion.identity);*
}
else if (activatorItems*.itemName.Contains(“sandtile”))*
{
objectPooler.Instance.SpawnFromPool(“SandTile”, activatorItems*.itemPos, Quaternion.identity);*
}
else if (activatorItems*.itemName.Contains(“watertile”))*
{
objectPooler.Instance.SpawnFromPool(“WaterTile”, activatorItems*.itemPos, Quaternion.identity);*
}

}
}

}
yield return new WaitForSecondsRealtime(1f);
StartCoroutine(“CheckActivation”);

}
}
So lets say I have a 1000x1000 tiles, so its iterating over a million tiles. And every single iteration I get a lag spike. I’m just not sure how I could clean this up to make it more performance friendly

So lets say I have a 1000x1000 tiles, so its iterating over a million tiles

Are you saying that activatorItems.Count is equal to 1,000,000 ? (⊙_⊙’)

A very first step would be to store the correct IDs once and reuse them in the coroutine.

private string[] spawnIDs;

private void Awake()
{
    FillSpawnIDs();
}

void FillSpawnIDs()
{
    if(activatorItems.Count == 0)
        return ;

    spawnIDs = new string[activatorItems.Count];
    for(int i = 0 ; i < activatorItems.Count ; i++)
    {
        if (activatorItems_.itemName.Contains("grasstile"))       spawnIDs *= "GrassTile";*_

else if (activatorItems_.itemName.Contains(“sandtile”)) spawnIDs = “SandTile”;
else if (activatorItems.itemName.Contains(“watertile”)) spawnIDs = “WaterTile”;
}
}_

IEnumerator CheckActivation()
{
if(activatorItems.Count == 0)
return ;

WaitForSecondsRealtime wait = new WaitForSecondsRealtime(1f);
float sqrDistance = distanceFromPlayer * distanceFromPlayer;

while(true)
{
for(int i = 0 ; i < activatorItems.Count ; i++)
{
if ((plrtransform.position - activatorItems*.itemPos).sqrDistance < sqrDistance)*
objectPooler.Instance.SpawnFromPool(spawnIDs_, activatorItems*.itemPos, Quaternion.identity);
}
yield return wait;
}
}*

But even with this small optimisation, you will have lags with 1 million objects to process. Either do the computation over several frames, or try to implement an Octree to reduce the number of tiles to loop over._