Reputation: 39
The only reason I'm posting this is because I actually believe that my code perfomance is being affected by this code block where I use a foreach loop inside another one.
I was wondering if anyone would suggest anything different that could help the performance or perhaps point out some other flaws in the code.
public override void DisplayScore()
{
byte MessageLocation = 0;
foreach (var kvp in PlayerScores.OrderByDescending((s => s.Value)))
{
if (MessageLocation == 5)
break;
if (MessageLocation == PlayerScores.Count)
break;
foreach (var player in PlayerList.Values)
{
SendMessage(MessageLocation, "My text");
}
Score++;
}
}
As you can see, it's just displaying the top 5 scores (in different locations) from a dictionary in a descending order and sending them to a list of players from another dictionary.
Upvotes: 2
Views: 103
Reputation: 1923
I don't think that the double loop is the problem. I suggest to check the LINQ query PlayerScores.OrderByDescending((s => s.Value))
. Depending on the numbers of scores this might take its time to order, espesially if the values come from a dictionary. The internal structure of a dictinary makes it expensive to enumerate through keys and values.
You can test it with the following code (slightly improved) and Visual Studio 2015, where it can be seen, how long single execution steps take:
public override void DisplayScore()
{
var scores = PlayerScores.OrderByDescending(s => s.Value).Take(5).ToArray();
foreach (var kvp in scores)
{
foreach (var player in PlayerList.Values)
{
SendMessage(MessageLocation, "My text");
}
}
}
Upvotes: 1
Reputation: 2382
Instead of nested for loops you may gain some performance by adding the scores to a list and then sending them to the players eg:
//List containing player and score
foreach (var kvp in PlayerScores.OrderByDescending((s => s.Value)))
{
//Add scores to list
}
foreach (var player in PlayerList.Values)
{
//Send scores to players
}
Upvotes: 0