should i allocate the memory once?

Started by
4 comments, last by Cygon 18 years, 10 months ago
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)
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
moe.ron
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?
In just about every situation, the first one is preferable.
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.
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-
Professional C++ and .NET developer trying to break into indie game development.
Follow my progress: http://blog.nuclex-games.com/ or Twitter - Topics: Ogre3D, Blender, game architecture tips & code snippets.

This topic is closed to new replies.

Advertisement