My 2 cents embedded...

> -----Original Message-----
> From: David [mailto:[EMAIL PROTECTED]
> Sent: Tuesday, November 09, 2004 2:40 PM
> To: [EMAIL PROTECTED]
> Subject: [c-prog] Code Efficiency
>
>
> Could this group shine some light on a debate we are having.  Given the
> two sets up code, which both do the same thing:
>
>     CustomType* ct;
>
>     ct = (CustomType*) malloc(sizeof(CustomType));
>     memset(ct, 0, sizeof(CustomType));
>
> or
>
>     CustomType* ct;
>     int sizeOfCustomType = sizeof(CustomType);
>
>     ct = (RingQueueType*) malloc(sizeOfCustomType);
>     memset(ct, 0, sizeOfCustomType);
>
> Which is more efficient in term of speed and size.
>
> My thought is that they both compile out to the same thing, while the
> second option gives you better insight into debugging (i.e. look at the
> sizeof value  [our embedded debugger can't evaluate methods
> (sizeof(CustomType)) ]).

You can use the first option plus adding conditional compilation so that
'sizeOfCustomType' is only visible in debug built.
   
    CustomType* ct;

#ifdef <your debug flag>
    int sizeOfCustomType = sizeof(CustomType);
#endif

    ct = (CustomType*) malloc(sizeof(CustomType));
    memset(ct, 0, sizeof(CustomType));


> The argument against is that the second option uses an extra int value,
> therefore increasing stack size. 

You can declare sizeofCustomType as const int.  As long as its address is
not referenced, the optimizer would most likely optimize it away.


> Some believe, which may be true
> depending on optimization settings, that the first is less efficient
> from a speed standpoint because it calls sizeof() an extra time.

sizeof is not a function call.  For most cases, I believe the evaluation is
done at compile time.


> Any thoughts?  Replace the sizeof() call with any frequently used call
> in a given method.  I.E. is it better to set a variable based on a
> single call and then re-use the variable, or make multiple calls to the
> same method, with the same paramters.
>
>     doSomething(customCall(constantVal););
>     doSomethingElse(customCall(constantVal););
>     doYetAThirdThing(customCall(constantVal););
>
> or
>
>     int customCallVal = customCall(constantVal);
>
>     doSomething(customCallVal);
>     doSomethingElse(customCallVal);
>     doYetAThirdThing(customCallVal);

IMHO, these are not good examples for illustration.  sizeof() is not
function call but customCall() can be.  If customcall has side effects, the
two fragments of codes could produce different results.

HTH
Shyan





To unsubscribe, send a blank message to <mailto:[EMAIL PROTECTED]>.


Yahoo! Groups Sponsor
ADVERTISEMENT
click here
Web Bug from http://us.adserver.yahoo.com/l?M=294855.5468653.6549235.3001176/D=groups/S=:HM/A=2376776/rand=456412714


Yahoo! Groups Links

Reply via email to