home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 33,050 of 33,346   
   Wil Evers to Andy Lutomirski   
   Re: Vector sizes and other missed optimi   
   16 May 13 16:47:07   
   
   From: bouncer@dev.null   
      
   Andy Lutomirski wrote:   
      
   [snip]   
   > template   
   > class Vec   
   > {   
   > public:   
   [snip]   
   >   size_t size() const { return len_; }   
   >   T &operator [] (size_t pos) { return data_[pos]; }   
   > private:   
   >   size_t len_;   
   >   T * data_;   
   > };   
   >   
   > template   
   > void IncrementVec(Vec &v)   
   > {   
   >   for (size_t i = 0; i < v.size(); i++)   
   >     ++v[i];   
   > }   
   >   
   > void f1(Vec &v)   
   > {   
   >   // This is slow -- the compiler can't figure out that data_[i]   
   >   // does not alias len_;   
   >   IncrementVec(v);   
   > }   
   >   
   > void f2(Vec &v)   
   > {   
   >   // This is fast -- type-based alias analysis works.   
   >   IncrementVec(v);   
   > }   
   >   
   > The code generation for f1 loads len_ on every iteration of the   
   > loop.   
      
   [snip]   
      
   > Are there any ways, idiomatic or otherwise, to tell a compiler (even   
   > in theory) that data_ can't point to len_?  Adding a restrict   
   > qualifier to data_ has no effect in g++ (correctly AFAICT -- data_   
   > isn't a function parameter).   
      
   What about fetching the size only once, and storing it in a local   
   variable:   
      
   template   
   void IncrementVec(Vec &v)   
   {   
     size_t sz = v.size();   
     for (size_t i = 0; i < sz; i++)   
       ++v[i];   
   }   
      
   I would expect any halfway decent compiler to detect that the address   
   of the local variable 'sz' is not taken, and therefore cannot be   
   modified by incrementing the vector's elements.   
      
   Hope this helps,   
      
   - Wil   
      
      
   --   
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca