structure initialization

J

junky_fellow

Guys,

typedef struct {
unsigned int count;
unsigned short id;
unsigned char cell[3];
} XYZInfo;

#define INFO_ITEM \
{ 0x7080A000, 0xB990, { 0x20, 0x30, 0x40 }}

func (void)
{
static XYZInfo s_itemInfo = INFO_ITEM; /* case 1 */
XYZInfo itemInfo = INFO_ITEM; /* case 2 */
..
..
}

My question is which one is better in terms of cpu time. I believe,
for case 1, the structure is initialized at compile time and should be
more efficient than case 2, where the structure will be initialized at
run time.
Is that right ?
 
C

Chris Dollin

Guys,

typedef struct {
unsigned int count;
unsigned short id;
unsigned char cell[3];
} XYZInfo;

#define INFO_ITEM \
{ 0x7080A000, 0xB990, { 0x20, 0x30, 0x40 }}

func (void)
{
static XYZInfo s_itemInfo = INFO_ITEM; /* case 1 */
XYZInfo itemInfo = INFO_ITEM; /* case 2 */
..
..
}

My question is which one is better in terms of cpu time. I believe,
for case 1, the structure is initialized at compile time and should be
more efficient than case 2, where the structure will be initialized at
run time.
Is that right ?

It's true that case (1) will initialise s_itemInfo exactly once [1], and
that case (2) will initialise [a new] itemInfo once per call of `func`.

I would expect the choice between them to be more a matter of
which was the /correct/ use than which was the /fastest/ use.
In case (1), changes to `s_itemInfo` are pervasive; changes to
it will be visible in the next call of `func`. What's more, if
`func` turns out to be recursive, then the nested call will fiddle
with the outer call's variable, since it's just the one variable.

In case (2), each call of `func` gets its own private `itemInfo`,
which it can mutate to its heart's content without disturbing
other funcs infos.

Myself, I'd use (1) if s_itemInfo was supposed to be some kind
of constant, and (2) if it was a varying variable.

[1] Of course if there are no /uses/ of s_itemInfo then the compiler
can throw it, and its initialisation, away. So "exactly once" has
more fur than "exactly" might suggest.

--
"There remains, as the Lord Gulhad indicated, a The Lord Toshin
third possibility." /The Demon Breed/

Hewlett-Packard Limited Cain Road, Bracknell, registered no:
registered office: Berks RG12 1HN 690597 England
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,111
Latest member
KetoBurn
Top