Is there any speed difference in accessing a static and a dynamic array ?
int *array1 = malloc(100*sizeof(int));
Maybe the speed difference is too little and the only case to see it, is when the loop is giant.
For most systems, the only difference is the overhead due to the call to malloc.
On some embedded systems, there can actually be different types of memory (slower flash memory for example) in which there can be a real difference in access time. But on PC's, memory is memory.
Sure, memory is memory, but aren't arrays more likely to be kept in the CPU cache than dynamic memory? If it's in the CPU cache, then it would be much faster.
The CPU cache (in x86 processors) will cache stack, globals or local variables exactly the same way - first time the value is read, it gets loaded into the cache, and as long as that location in the cache isn't needed for something else, it stays in there.
Originally Posted by cpjust
The only situation where you'd set the memory to be uncacheable is where you have a lot of writes and few reads, and there's hardware on the other end of the memory that requires the writes to be fully out in memory before the data can be used by the hardware - this is typically how frame-buffers work for graphcis chips, for example - it's very rare that we read from the graphics frame buffer, but writes are very common.
But general memory used purely for CPU data or code will be cacheable on any modern(ish) processor, and the way that the memory was allocated (stack or heap) should not make any difference to this.
It is a slightly different story if we have small amounts of memory scattered about all over the place, say in a linked list, or some other structure with further pointers [e.g. a struct that holds a string which in turn is dynamically allocated] - here we can get into a situation where the data referenced by a pointer is not in the cache, and because the memory is (potentially) fragmented all over the place, the memory fetched to read a link in the linked list will not fetch anything particularly useful NEXT to the link we follow - because the data is scattered all over the memory [particularly if it is a linked list which lives for a long time and has some of the data added and removed during that time].