Jump to content
  • Advertisement
Sign in to follow this  
Genjix

should i allocate the memory once?

This topic is 4825 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

if i need a single object repeatedly throughout a program should i allocate and re-allocate or should i just create it once? i.e
	Object obj;
	// keep it there and initialize and use as needed

	Object *obj;
	// object is needed
	if(obj)
		throw ObjectIsntDeleted();
	obj = new Object();
	delete obj;

which is better and why? (ignoring the dangers of pointers)

Share this post


Link to post
Share on other sites
Advertisement
It really depends on what you are using it for. I feel like thats a cheesy answer, but the question is kind of vague... Do you have any specific example that you are considering?

If its some kind of a managing class, I would just instantiate it once and keep it throughout the program lifetime. Many other things I would just create when needed

Share this post


Link to post
Share on other sites

class AnimatedSprite
{
public:
void PlayAnimation(const string &animname , int n);

private:

struct PlayingAnimation
{
AnimationIterator anim_it;
bool isplaying;
int play_count;
}playing;
};



when i play the animation i set the bool and initialize anim_it

OR

class AnimatedSprite
{
public:
void PlayAnimation(const string &animname , int n);

private:

struct PlayingAnimation
{
AnimationIterator *anim_it;
int play_count;
}playing;
};



use the anim_it as the bool and create and allocate as is needed. Which is a better solution?

Share this post


Link to post
Share on other sites
ok thanks. it was kinda a cpu vs memory issue (since there are a lot of these kinds of objects around). I know its being kinda nitty gritty but I thought I might be losing out by not asking.

Share this post


Link to post
Share on other sites
I'd also say go with the first solution. The second one is just too error prone - if you're facing performance issues later on, go with object pooling (which can be easily equipped to existing classes as seen in the Loki Library, but I don't think that would ever be the case here, stack allocation is blindingly fast.

-Markus-

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!