4 ms·
The problem with using void* pointers is that every access to an element costs one extra dereference operation. By using C++ templates, the compiler can create
by rbonvall 15y ago
The problem with using void* pointers is that every access to an element costs one extra dereference operation. By using C++ templates, the compiler can create object code specifically compiled for each data type, without the need for pointers. (On the other hand, this can make C++ binaries much larger).
- mklencke 15y agoIn this case, I'm not storing void pointers in the data structure, but I'm using the void pointer as a direct address into "elements". The memory layout is just a sequence of items of length elem_size. vector_push copies the item into that memory (and doubles the size of "elements" with realloc when necessary).
- anonymous246 15y agoSo you have a memcpy() call in vector_push? I wonder if that's less efficient than a straight-up assignment for small objects such as integers. The C++ equivalent can be further optimized during instruction generation by keeping things in the CPU registers as long as possible. In your C case, the int has to be written to memory before memcpy can load it into its buffer.
- mklencke 15y agoTrue, but that can be overcome by another function that just gives you an address to put a new item. You would say, for example: *(int *)vector_expand(v) = 2;
- anonymous246 15y agoThis is a super-unclean API, but that's just IMHO. We'll just have to agree to disagree that what you've shown above is an acceptable API for a vector module.
- mklencke 15y agoI'm just making it up as I go along, it's not the prettiest thing. What would you do, in C?