|
-
May 1st, 2014, 09:21 AM
#22
Re: passing an array as a pointer to a function
 Originally Posted by laserlight
Oh, and a thought came to mind: conceptually, it still is a pointer dereference according to the semantics, even before you start passing it around.
the issue is not whether a dereference conceptually occurs or not, the point is if such a dereference implies a memory access to the pointer value or not.
 Originally Posted by zizz
The result is that there's no difference in performance of the arrays. I know one cannot draw general conclusions from tests like this but at least Microsoft's C++ implementation didn't stumble on the pointer indirection you claimed is ALWAYS present and detrimental to efficiency. Here it wasn't.
the fact that is theorically "present" does not exclude the possibility that it will be optimized anyway (*). In order to show the effect of that indirection you should force the compiler to perform a new "access" for each iteration, something like this:
Code:
#include <vector>
#include <array>
#include <iostream>
#include <ctime>
struct A{ int c[10]; A(){ std::cout << "we need a type with a nontrivial ctor for fair testing ...\n"; } };
int foo( int i ) { static A c; return c.c[i]++; }
int bar( int i ) { static std::vector<int> c(10); return c[i]++; }
int main( int argc, char* argv[] )
{
auto fptr = argc % 2 ? foo : bar; // just to avoid inlining
int result = 0;
fptr(0); // force static initialization
auto time = std::clock();
for( int c = 0; c < 100000000; ++c ) result += fptr( c % 10 );
auto duration = std::clock() - time;
std::cout << ( fptr == foo ? "foo" : "bar" ) << ": " << result << " in " << duration;
}
on my system ( ~10 runs each, both interleaved or not ), this gives a stable avarage slowdown of 46% for the vector version ( the slowdown increases to 60% if we replace A with a plain array due to the static initialization code as the asm shows, hence the non trivial constructor ).
EDIT: (*) to clarify, in your code, the indirection OReubens alluded to does occur ( so it is correct to say that it always occurs when an allocated array is involved ), it just occurs only once instead of for each and every iteration, hence making it to disappear in your measurement.
Last edited by superbonzo; May 1st, 2014 at 09:53 AM.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|