Thread: Optmization question

  1. #1
    Registered User
    Join Date
    Jun 2003
    Posts
    7

    Post Optmization question

    Which is faster:

    * creating an object statically (ex. MyObject object(foo); )
    * creating an object dynamically (ex: MyObject *object = new MyObject(foo); )

    If creating an object dynamically is slower, how much slower is it?

    Thank you!

  2. #2
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    Run a test and let us all know.

    Todd

  3. #3
    Registered User
    Join Date
    Dec 2006
    Location
    Canada
    Posts
    3,229
    creating it dynamically is slower because of memory management (allocation). Statically allocate something takes no time AFAIK (except the time spent in the constructor).

  4. #4
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    As for how much, that depends on your system's memory management implementation.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  5. #5
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    By "statically" I see you simply mean as a local variable.

    The rule is: Don't use 'new' if you don't need to.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  6. #6
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by cyberfish View Post
    creating it dynamically is slower because of memory management (allocation). Statically allocate something takes no time AFAIK (except the time spent in the constructor).
    That's not true.

    The actual time it takes to create an object depends on how the application manages memory in its address space, and that depends on compiler/library implementation, the operating system, and the actual resources available to your program. Creating any object requires some memory to be obtained or supplied. The only thing that changes is when it happens, and what section of memory (eg what segment) the memory for the object is obtained from.

    Statically allocating something means that is created before the first time it is used (i.e. a global object) which is a different thing from Darkwraith's first example.

    The relative speed of different mechanisms of creating an object is implementation dependent. There is no universal guarantee that any particular mechanism is faster. In practice, a static allocation is often faster because the compiler/linker can do some work to optimise things. There are also some optimisations a compiler can do with the process of creating an object locally to a function. However, there is still no universal guarantee that any option for creating an object will always be faster than another.

  7. #7
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    For tiny objects, the overhead of allocating memory can be substantial. For large objects, the time used for constructing the object is much greater, so the allocation disappears in the noise. Obviously, somewhere in between are "medium sized objects", where the allocation and construction takes about the same amount of time.

    Ok, so for the pedants in this forum: Actually, the size of the object itself is technically irrelevant, the time the constructor takes is much more important - consider this:
    Code:
    // Small object, slow construction. 
    class slowconstructor 
    {
    public:
       slowconstructor(int n) { 
          f = 1.0;
          for(int i = 0; i < n; i++) 
             f = f * i;
          };
    private:
       double f;
    };
    
    // Large object, fast constructor. 
    class fastconstructor 
    {
    public:
        fastconstructor(n) {
            len = 0;
        }
    private:
        int array[100000];
        int len;
    };
    As iMalc says: If you don't need to use new, then don't. The trouble is of course "knowing" when you need to use new...

    The problem with NOT using new is that the code uses up stack-space, which is more limited that free-storage (heap-space). The heap, in a modern OS, can be more than a gigabyte. Whilst there is no technical reason why the stack can't be huge too, it's normally limited to a few megabytes. Running out of stack is also "worse" than running out of heap-space, as it's impossible for the code to recover from a "out of stack" scenario - out of heap can be detected and at least some sort of resemblance of recovery is possible.

    Obviously, real-time OS's may be even more constrained when it comes to both stack and heap-sizes, but generally, the heap is a much better place to put "large" objects.

    Finally, there is one other consideration: If you use a pointer, the compiler will have to dereference the pointer to get to the actual object. This can lead to further reduction in performance - again, more noticeable on objects where the member variable or member function is "trivial" and disappears of the member variable or member function requires a lot of CPU-time to get the work done.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  8. #8
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    The stack has the guarantee that objects are deallocated in reverse order of their allocation, while the heap must support any order of allocation/deallocation. That makes the memory management for the stack far, far easier than for the heap, and thus faster. (The management of the stack is a single pointer in pretty much every piece of hardware out there. The management of the heap is subject to much research and use-case-specific optimization.)
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > Which is faster:
    Does it matter?
    The first rule of optimisation is to make it right, before you think about trying to make it fast.

    Use the form which is most correct in the circumstance in which you're using it.

    Besides, as matsp demonstrates, there is no single clear-cut answer to the problem.

    Further to matsp's comments on the stack, consider that growing the stack by a large amount can cause a large number of page faults. IIRC, windows grows the stack 4K at a time when it's necessary to do so, up to however many pages are needed to satisfy the local stack frame. However, this only happens once, so when you've got the large stack, there is no further hidden cost. How stacks grow in other operating systems (if at all) is left as an exercise for the reader
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  10. #10
    Registered User
    Join Date
    Jan 2007
    Posts
    330
    Quote Originally Posted by Salem View Post
    > Which is faster:
    Does it matter?
    The first rule of optimisation is to make it right, before you think about trying to make it fast.

    Use the form which is most correct in the circumstance in which you're using it.

    Besides, as matsp demonstrates, there is no single clear-cut answer to the problem.

    Further to matsp's comments on the stack, consider that growing the stack by a large amount can cause a large number of page faults.
    Well, allocating a large amount on the heap can cause a large number of page faults too. IMO when comparing stack vs heap allocations there is really a clear cut answer if you know there is hardware support for the stack. The stack will be faster....
    It gets shady when there is only software support for allocating stackframes because the obvious way then is to allocate so called "activation records" dynamically...

  11. #11
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    >> Use the form which is most correct in the circumstance in which you're using it.

    In cases where both will work, the local variable is almost always the most correct choice.

  12. #12
    Registered User
    Join Date
    Jun 2003
    Posts
    7
    Thank you for all your help!

    This pretty much answered my question.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Alice....
    By Lurker in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 06-20-2005, 02:51 PM
  2. Debugging question
    By o_0 in forum C Programming
    Replies: 9
    Last Post: 10-10-2004, 05:51 PM
  3. Question about pointers #2
    By maxhavoc in forum C++ Programming
    Replies: 28
    Last Post: 06-21-2004, 12:52 PM
  4. Question...
    By TechWins in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 07-28-2003, 09:47 PM
  5. Question, question!
    By oskilian in forum A Brief History of Cprogramming.com
    Replies: 5
    Last Post: 12-24-2001, 01:47 AM