Re: Vectors vs Arrays performance
On Jan 2, 7:55 pm, "Leigh Johnston" <le...@i42.co.uk> wrote:
"James Kanze" <james.ka...@gmail.com> wrote in message
news:d215cd97-7eb5-4b38-bafb-bada3175bc0e@k17g2000yqh.googlegroups.com...
On Jan 2, 2:49 pm, "Leigh Johnston" <le...@i42.co.uk> wrote:
Accessing a vector's contents via operator[] will always be
slightly slower than accessing a local (stack based) array
via [] as you have to dereference a pointer with the vector
version.
That's bullshit. You have to dereference a pointer in both
cases. In the case of indexing, you have to calculate the
address (both for stack based and for std::vector), and
because these calculations are hidden in some functions with
std::vector (and probably do bounds checking as well), it's
harder for the optimizer to get its hands on them. On the
other hand, if you're using iterators, your code with
std::vector is basically what the optimizer will do with
indexing into a built-in array.
It is not bullshit, in the case of the stack array it is
simply an offset from the current stack pointer, no
dereference required,
You can't access the value without having its address. And the
value is in memory, so accessing it involves dereferencing the
address.
take a look at assembler output if you do not believe me, you
should see an extra instruction for the dereference of vector
operator[] compared to the stack array []. If you are using a
pointer/reference to the array then they will be the same.
int main()
{
volatile int output;
int a[10];
std::vector<int> v(10);
_asm int 3;
output = a[0];
_asm int 3;
output = v[0];
_asm int 3;
}
What on earth is the volatile doing in there? And the _asm?
outputs (VC++ Release Build):
00020 cc int 3
; 19 : output = a[0];
00021 8b 44 24 20 mov eax, DWORD PTR _a$[esp+72]
00025 89 44 24 0c mov DWORD PTR _output$[esp+72], eax
00029 cc int 3
; 21 : output = v[0];
0002a 8b 44 24 14 mov eax, DWORD PTR _v$[esp+76]
0002e 8b 08 mov ecx, DWORD PTR [eax]
00030 89 4c 24 0c mov DWORD PTR _output$[esp+72], ecx
00034 cc int 3
Notice the extra instruction?
I noticed a lot of extra instructions: a volatile, and some
_asm, to begin with.
If you'd have read the rest of my posting, you'd have seen that
I explained what is actually relevant, not some hypothetical
case which doesn't correspond to anything.
--
James Kanze