Turn on your disassembler when you enter your function, and step through the 2 cases.
The local variable (stack based) will require 0 extra cycles -- you won't even see where the allocation comes, because the function will allocate all the local variables in 1 cycle by just moving the stack pointer, and free all the local variables in 1 cycle by restoring the stack pointer. It doesn't matter if you have 1 or 1000 local variables, the "allocation" takes the same amount of time.
The malloc variable ... well, you will quickly get bored click-stepping through the thousands of instructions that are executed to get memory from the system heap. On top of that, you might notice that the number of cycles varies from call to call, depending on how many things you have already allocated from the heap, as malloc requires a "search" through the heap structure every time you ask for memory.
My rule of thumb: always use the stack if possible, instead of malloc/free or new/delete. In addition to faster performance, you get the added benefit of not having to worry about memory or resource leaks. In C this just means forgetting to call free(), but in C++ exceptions can ruin your day if something throws an exception before you call delete. If you use stack variables, this is all handled automatically! However, only use the stack if you are talking about "small" pieces of memory (bytes and KB) and not huge objects (not MB or GB!). If you are talking about huge objects anyways, you are not talking about performance any more and you will probably not be calling free/delete in the same function call anyways.
answered 2012-10-31T00:38:20.640