malloc vs std::vector

please could anyone tell me is malloc a better way of declaring a variable 2d array or std::vector(i mean to ask which ones faster ?)

Malloc right? Can someone confirm that?
When You do a malloc all of it is allocated all toghether and thus happens faster. Whereas in a vector it gets allocated as you insert.

stl has been written in faq as slow so vectors are slow ?

Malloc is faster than using vector because, malloc just allocates raw memory with some garbage value in it. There is no type checking . It just blindly allocates a chunk of memory and returns the (void *)pointer.

When it comes to vector, one thing I am sure is it fills all the elements with all zeroes. So, this definitely takes some time. Also , it is just not some raw memory.

So, definitely malloc is faster than vector.

1 Like

The question should make more sense if it were malloc vs new, because new is the equivalent keyword of malloc if you want dynamic memory allocation. Vector is another container provided by C++. malloc and new are just ways to get memory for the same container array.

Vectors and arrays are different containers.

Compared to arrays, yes vectors might be somewhat slow.

2 Likes

Hello,

I guess the apparent slowness of vectors towards dynamically declared C-style arrays with malloc is simply on the “construction”.

It has what it’s known as “construction overhead”, which means it is only slower during the declaration+initialization process, but, afterwards, it’s possibly more effective than arrays, but, as in everything in Programming, I guess this is also highly dependent on the usage that its being given to the container itself.

If you are constantly resizing or reallocating it, opposed to only doing insertions and or look-ups, it is a bit of overkill to use C-style arrays, which would imply heavy usage of functions like resize or realloc, while vectors handle such things internally and possibly in a more optimized way I think.

You can read a very interesting discussion on this matter here:

Malloc vs STD::vector: A comparison

Personally I have always used std::vector and never found it to be a bottleneck if the code that manipulates it is well designed :slight_smile:

Best regards,

Bruno

1 Like