2
I have a scenario here where I create a list to check some items, and I need to clear this list inside the loop, and I got some questions regarding the performance
I must check the list before I clean up ? (
.Any() ou .Count > 0 ?
) not to execute the.Clear()
no need? Or If may be worse than Clear ?Move list creation into for? (I think it’s less
efficient, create an object instance at each loop.)Leave as is, call the clear without checking if the list there content.
var gameIds = new List<int?>(); var gameId = gameSession?.GameId % 100000; for (int i = 0; i < Messages.Count; ++i) { var message = Messages[i]; gameIds.Clear(); //.... mais código... }
Before you think of the most efficient way to clear the list, write the code that does what you need. When you have that code and it works, run your project and use a profiler to see if that piece of code is even a problem. Premature optimization is a problem because you think it’s solving a problem that may not actually even exist.
– Omni
The code is ready and is going into production, I was asked here if it would be better to clear this list or not before performing the check. Sorry if I was unclear in the content of the question. Thank you.
– Thiago Loureiro