Skip to main content
GameDev.net gamedev.net
🔒 Locked

[.net] Question about compile and run time I think

Started by thallish Nov 8, 2007 at 3:36 AM 2 replies 850+ views
Original Post
thallish
thallish
Hi I was wondering if anyone could give the cons and pros of doing as in the following two examples. If I always create a new empty List ( or some other object/value ) does it at all have an impact if the declaration is done as

class Some
{
    List<whatever> aList = new List<whatever>();

    public Some()
    {}
}

instead of doing

class Some
{
    List<whatever> aList;

    public Some()
    {
        aList = new List<whatever>();
    }
}

If both methods are alright when should the one be used over the other? does it matter? Thanks!
regards/thallishI don't care if I'm known, I'd rather people know me
ToohrVyk
ToohrVyk
The first is faster (to write) when all constructors initialize the list the same way. The second is faster (to execute) when constructors initialize the list differently. Otherwise, they are equivalent.
TheGilb
TheGilb
Correct me if I'm wrong but neither of the examples will compile. In the first example you are attempting to initialise a class member with operator new. The correct code would declare aList as a static member which you could define in a corresponding implementation file. This would allocate aList in static storage in the executable, so there would be no overhead of your constructor during runtime.

In the second example you are attempting to set aList to a new List template using operator new which returns a pointer to the allocated memory where the List object was created. The correct code would declare aList as a List template pointer, then the code in the constructor would work as expected. The second example would have runtime overhead of the small object allocation, which isn't much.

Which method you use depends on the class object itself. For the given example (a class object called 'Some') the appropriate usage is not at all obvious. When data is placed in static storage it is accessible in the global scope. Perhaps now I have explained it a little more it has become obvious which method is more appropriate and when? If not then I highly recommend reading a few chapters of Thinking in C++ by Bruce Eckel (Google search it, it's a free download!). Mr Eckel explains it a lot better than I ever could ;-)

Hope that helps! ( it probably doesn't ... )
ToohrVyk
ToohrVyk
Quote:
Original post by TheGilb


This is Sparta C# (no colon after public, no pointer semantics for new, no semicolon after class definitions, a standard library container called List).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.