简体   繁体   中英

How fast is memory access to a vector compared to a normal array?

I have a function that is called thousands times a second (it's an audio effect) and I need a buffer for writing and reading audio data. Is there a considerable difference in performance between declaring a float array as a normal array or as a vector?

Once declared, my array is not resized during the audio loop, but at the initialization phase I don't know the exact length because it's dependant on the audio sampling rate. So, for example, if I need a 2 seconds audio buffer for a sampling rate of 44100 Hz, I normally do this:

declaration:
  int size;  
  float *buffer;

void init (int sr)
{
  size = sr * 2;
  buffer = new float[size]();
}

~destroy()
{
  delete [] buffer;
}

Allocating memory dynamically has a small cost, as does the later deallocation, but you've illustrated use of new already so your costs are equivalent to vector with an adequate initial size or reserve call in every way.

Once allocated the operations can be expected to be as fast in any optimised build, but you should profile yourself if you've any reason to care.

It's not relevant to your new -ing code, but FYI there at least a potential difference due to addressing - a global or static array might have the virtual address known at compile time, and a stack based array might be at a known offset from the stack pointer, but on most architectures there's no appreciable performance difference between those and indexing relative to a runtime-determined pointer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM