I am programming a type of game in C# and I want to know what would be a better approach for memory usage. Right now I have it so it goes through a while loop and while the game is running it will check for certain things (is this person dead, etc), sleep for one second, then try again. Once the game is over the while is set to false and it exits the method. Would a timer be a better way of doing this? I’m noticing memory issues sometimes when I run this game.
Share
The
whileloop approach is probably not your problem.Timeris in fact a bit heavier than this approach, and will consume more system resources, but this will be a one-time allocation. In other words, changing your main loop code from one structure to the other is unlikely to change your application’s memory profile significantly.Have you tried profiling your application’s memory usage? You’re likely holding on to objects that you don’t need anymore. A profiler might be able to help you determine where.
(In case you are curious, using a
Timerwill likely have a very small performance impact, since each iteration will cause a function pointer call, which the CPU and JIT-compiler cannot optimize very well. Using awhileloop means that your code is always running; theThread.Sleep()call can be optimized fairly well since it is not through a function pointer. Considering that theTimerapproach is also likely to result in less readable code, I would strongly suggest that you continue using awhileloop.)