Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Creating a new sf::Event object in each loop?  (Read 2659 times)

0 Members and 1 Guest are viewing this topic.

keyforge

  • Jr. Member
  • **
  • Posts: 65
    • View Profile
Creating a new sf::Event object in each loop?
« 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?
Need a place to upload your code, files or screenshots? Use SFML Uploads!

thePyro_13

  • Full Member
  • ***
  • Posts: 156
    • View Profile
Creating a new sf::Event object in each loop?
« Reply #1 on: October 23, 2011, 08:01:04 am »
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.

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Creating a new sf::Event object in each loop?
« Reply #2 on: October 23, 2011, 10:11:50 am »
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.
Laurent Gomila - SFML developer

Nexus

  • SFML Team
  • Hero Member
  • *****
  • Posts: 6287
  • Thor Developer
    • View Profile
    • Bromeon
Creating a new sf::Event object in each loop?
« Reply #3 on: October 23, 2011, 01:06:22 pm »
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.
Zloxx II: action platformer
Thor Library: particle systems, animations, dot products, ...
SFML Game Development:

 

anything