Quote:
Originally Posted by CoderMan
Is using dynamic memory allocation with malloc (in C) significantly slower than regular assignments?
|
Using malloc and free take some time, each time you call them. But if you aren't allocating and freeing things a super large number of times per run of your program, that doesn't matter much.
I think you are also asking about the relative performance after allocation, I think comparing an array of char as a member of a struct vs. a pointer to char as a member of a struct.
The code will be different and one might be faster than the other, and it seems more likely that this performance difference would matter rather than the malloc overhead mattering.
Depending on exactly how you use it, a char* as a structure member might be faster or slower than a char[256] as a structure member. More often the char* would be slower.
Odds are, other aspects of your code take long enough that this difference wouldn't matter.
Quote:
(the memory for the structs themselves is assigned dynamically as needed).
|
Do you know the char array length for a given struct at the time you malloc that struct? If so, it should be practical to make the variable length char array directly a member of the struct. Just make it the last member, make it as small or smaller than the smallest valid size and know the difference between sizeof() the struct and the true size is the difference in that array length.
Some C implementations allow a char array dimensioned [] to be the last member of a struct others allow [0]. I don't recall which is correct. When I do such things, I tend to use [1] instead.
Quote:
I also read somewhere that malloc can be slower than the non-dynamic allocation, because it has to scan for free memory first. (?)
|
Would you allocate the char array just once per struct? If so, the work inside malloc is trivial. Your comparing 10 to 60 malloc calls to allocate the structs with included char arrays, vs. 20 to 120 calls to allocate the structs with separate char arrays.
Quote:
Originally Posted by jailbait
Malloc is a kernel call and the kernel has to scan its free memory queue and move some free memory to your program's exclusive use.
|
More accurately, malloc
can be a kernel call. Most calls to malloc find memory already committed to the process, and do not involve any kernel call. Some calls to malloc require kernel calls. In the context of the questions in the first post of this thread, it is a reasonable assumption that doubling the number of malloc calls by splitting each struct from its char array, while reducing the total memory allocated, will not increase the total number of kernel calls (more likely it would decrease it).