Reputation: 1
I come from a C/C++ background and am learning C# as I go along. I found this example online.
KeyboardState state = Keyboard.GetState();
...
previousState = state;
At first glance, it didn't seem like the most prudent way to do it. I changed it to this:
Array.Clear(pressedKeys, 0, 103);
Array.Copy(Keyboard.GetState().GetPressedKeys(), pressedKeys, Keyboard.GetState().GetPressedKeys().Length);
...
Array.Clear(prevKeys, 0, 103);
Array.Copy(pressedKeys, prevKeys, pressedKeys.Length);
But then I looked at the original code again and now I'm confused. To me, it originally looked like my way was better because I thought I wasn't leaving allocated memory spaces behind, but it seems like Keyboard.GetState() creates a new state object instead of just returning the reference to its own member, as it has to be called every game loop (I tested this). So if this is the case, either way would leave behind one unreferenced keyboard state object for the garbage collector to clean up: previousState's object in the sample, and the one returned in the function call in the first Array.Copy() in mine. If that's what's going on, mine's slightly worse because it holds two extra arrays and performs extra operations on them. Is this necessarily the case? Or do I have no idea what I'm talking about?
Upvotes: 0
Views: 321
Reputation: 808
KeyboardState is a struct. It's allocated on the stack and copied by value, so there is no GC involved unless you somehow box it onto the managed heap.
Write the code in the most natural way possible (the first way) and optimize your bottlenecks later when you have profiling data that actually shows there is a bottleneck.
Upvotes: 3