On 12/29/2009 9:18 PM,
wrote:
> +AMDG
>
> I have a question about execution speed between allocating
> storage dynamically with malloc() and doing so statically
> with arrays. Which is faster?
How long is a piece of string?[*]
Calling malloc() -- and perhaps free(), too -- will most
likely consume some execution time that a static allocation
would not incur. On the other hand, a large static allocation
might slow down the program's startup. Or not. Furthermore,
the trade-offs will be different on different C implementations.
My advice is that you not choose between allocation styles
(static, automatic, dynamic) because of speed, but make your
choice based on the "logical" needs of the program:
1) If you've got something whose size is known at compile
time, which needs to exist throughout all or most of
the program's execution, and of which you need exactly
one copy, static allocation is attractive.
2) If you've got something whose size is known at compile
time but whose use is associated with a particular
invocation of a function (that is, you only need it
while a function runs, and you need a fresh one for
each function call), automatic allocation is called for.
3) If you've got something whose size won't be known until
run-time, or which needs to be created in one function
call and persist after that function returns, use
dynamic allocation.
These aren't absolute rules, but useful guidelines. Since
you're in the process of learning C, I'd suggest you not worry
about the exceptions and corner cases just yet. Follow the
"rules" for the moment, but be aware that other considerations
(that you'll learn about later) may override them.
[*] Smart-aleck answer: strlen(piece).
--
Eric Sosman
lid