This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Optimization/clarity coding : what is gcc able to do for me ?


On Fri, 2005-01-14 at 11:25 +0100, Pierre Chatelier wrote:
> A last (more or less stupid) example:
> 
> Is it better to write :
> 
> vector<int> v(1000);
> for(int i=0 ; i<v.size() ; ++i)
>    v[i] = i;
> 
> or rather :
> 
> size_t size = 1000;
> vector<int> v(size);
> for(int i=0 ; i<size ; ++i)
>    v[i] = i;
> 
> In this last example, the question is about how the compiler can guess, 
> thanks to inlining and other things, that "size" won't be modified in 
> the loop, and that it does not have to call "size()" at each iteration. 
> This example may not be very relevant, because "size()" is certainly an 
> inlined accessor to a private attribute, so that there should not be 
> many performance regression. The question still arises for me, because 
> I do not know if it will be more efficient to access a local variable 
> "size" or the "distant" size attribute of the object.
Two notes:
1.  stdc++'s implementation of std::vector does not reference a class
member--it subtracts the end() iterator from begin().
2.  Can the compiler optimize the size() call away (after calling it
once)?  What if the vector was accessible in another thread?  The other
thread could modify the vector simultaneously.

-- 

Regards,
Nick G.



Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]