Initialization List Vs Static Const Initializing

269 views Asked by At

What is faster when creating 100+ newObjs:

//initialization list
    struct struct_Obj {
    ...tonsOfVars
    struct_Obj() : tonsOfVars(init) {}
    }

Or:

//static const already constructed, call the copy constructor(?)
static const struct_Obj defaultStruct_Obj = { tonsOfVars(init) };
struct_Obj newObj = defaultStruct_Obj

TonsOfVars would imply multiple different variables (from POD to structs/classes)

I would assume static const, since its calling the copy constructor (meaning 1 op?) vs calling each initializer in the initalization list?
Although the common response for this is "profile it", even doing so would not give me an explanation WHY it is faster.

2

There are 2 answers

0
swang On

I think it depends on the speed of constructor of tonsOfVars vs. copy constructor of tonsOfVars, if they are all compiler generated or doing shallow copy, then I can't think of why initialization list is not faster.

Depends on what types tonsOfVars are, you compiler's optimization can also make a difference.

2
Nemanja Boric On

It really depends on the types in tonsOfVars.

I would assume static const, since its calling the copy constructor (meaning 1 op?) vs calling each initializer in the initalization list?

It is calling one copy constructor for struct_Obj, but it still needs to call copy constructor for each field.

If they all are POD data, there would be no difference at all. However, in some types default constructors may be faster (or slower) than copy constructors, so that would make a difference.