SFML community forums
General => General discussions => Topic started by: keyforge on October 23, 2011, 04:19:03 am
-
Hello, everyone! I have a question about most SFML code I see. Why are they redeclaring an sf::Event object after while(Window.IsOpened()). Wouldn't this cause the sf::Event constructor to be called each time creating a new object and hurting performance slightly? Is there any difference in declaring sf::Event before the main window loop?
-
You reassign it a few times in the following while loop(PollEvent), so the hit from the first construct is pretty light by comparison. You also make the code more readable by having the variable declared closer to the point is is used at.
A tiny performance loss for a much larger maintenance benefit seems like a good trade off. You can declare it above the first while loop if you prefer, their's no technical reason that requires it to be recreated every frame like in the examples.
-
There are already some threads that discuss this point on the forum.
Basically, sf::Event is a POD type so there's no constructor/destructor. It takes zero CPU cycle to create/destroy a sf::Event on the stack.
-
Declare variables as late and as local as possible. If you don't need the tiny performance difference (and mostly you don't), variable recycling is not worth the worse readibility and higher error-proneness. In general, you should not sacrifice good code style for the sake of irrelevant micro-optimizations.