galinette
galinette

Reputation: 9292

C++ Allocate on stack without initialization

I am writing a program where speed optimization is critical. Every 1% speed increase is good.

In a function which is called a lot, I need a fixed size array of a (small) class MyClass. At the beginning, I used a std::vector. The whole thing is small (typically 256 items, the class size is 12 bytes, which means 3072 bytes if the array is 16-byte aligned)

Now it happens that:

So it should be even faster to both allocate on stack AND skip initialization. I can rewrite the class constructor if required but I do not know how.

Thanks,

Etienne

Upvotes: 1

Views: 960

Answers (1)

john
john

Reputation: 87959

You don't need initialization? So presumably MyClass has no constructor, and no data members that need constructing? In that case the compiler will not do any initialization anyway. So just use new.

If MyClass does have a constructor then you should consider why it does when, as you say, you don't need initialization.

If MyClass does have data members that need constructing (a std::string say) then I'd query your assertion that you don't need initialization.

But you're right on the other point, switching from vector to an array should save you some time.

Upvotes: 3

Related Questions