❔ Optimization thoughts on a loop.

Looking for potential ways to speed up this operation. Any thoughts? The entries of each HashSet will change regularly and this is iterated frequently.
public class MyClass { }
//This will aways have 4 entries.
private List<HashSet<MyClass>> _regions = new List<HashSet<MyClass>>();
private void Test()
{

for (int i = 0; i < 2000; i++)
{
CheckIndex(0);
if (i % 2 == 0)
CheckIndex(1);
if (i % 3 == 0)
CheckIndex(2);
if (i % 4 == 0)
CheckIndex(3);
}

//Logic
void CheckIndex(int index)
{
HashSet<MyClass> classes = _regions[index];
//do things to classes.
}
}
public class MyClass { }
//This will aways have 4 entries.
private List<HashSet<MyClass>> _regions = new List<HashSet<MyClass>>();
private void Test()
{

for (int i = 0; i < 2000; i++)
{
CheckIndex(0);
if (i % 2 == 0)
CheckIndex(1);
if (i % 3 == 0)
CheckIndex(2);
if (i % 4 == 0)
CheckIndex(3);
}

//Logic
void CheckIndex(int index)
{
HashSet<MyClass> classes = _regions[index];
//do things to classes.
}
}
5 Replies
canton7
canton72y ago
Which bit specifically are you looking to speed up? The only things that are actually in the code you posted are a loop, a modulo, and an array access. All of those are pretty fast
phaseshift
phaseshift2y ago
Have you benchmarked the general code? Are you sure this is a hotspot? This reeks of premature optimisation
FirstGearGames
I'm just curious if there's something that sounds out as 'could be better' double checking my work
phaseshift
phaseshift2y ago
well, if i%4==0 theres no point in checking i%2
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server
More Posts