c++ - Shall I optimize or let compiler to do that? -


What is the preferred method of writing the loops according to efficiency: way A)

  / * Here I am hoping that the compiler will optimize this code and every time it will not repeat through this loop / / (unsigned I = first string; size (); i & lt; anotherString.size (), + + I) {// do something}  

Or maybe I should do it like this: path B)

  unsigned first = firstString.size ( ); Unsigned second = second string. Size ();  

And now I can write:

 for  (unsigned i = first; i & lt; second, ++ i) {// something Doing}  

Another way I feel like a bad choice for two reasons: the scope is the pollution and verbility, but the advantage of ensuring that the size () for each object is applied once Will be done.

I usually write this code as:

  / * i is local for size loop / / (size_ty i = first string. Size ()), size = other string. Size (); I & lt; Shape; ++ i) {// do something}  

In this way I do not pollute the parent's scope and for each loop to run anotherString.size () Avoid calling.

This is especially useful for Iterators:

 for  (some_generic_type  :: forward_iterator it = archive.bugin (), end = collection .end (); it! = End; ++ it) {// do something with * this}  

Comments