For int
it won't make much difference in speed. Although the compiler could make some extra optimizations in certain cases - also when using const
for example.
It will matter if the objects are larger, and/or their copy constructor needs to be called.
Small parameter types like int
's other built-in types can be stored in registers directly in some cases. Using a pointer or a reference for such types wouldn't make much difference in speed (they take about the same space), except for some compiler optimizations.
is it slower to declare our iterator within the for loop, such as: for
( int i = 0; ... ) ( say we have a bunch of loops that could use the
same iterator within the same scope ), or is it better to declare it
in the outside scope, as a variable, such as int i; for ( i = 0; ...
);? My logic is that it's faster to declare it outside, if we could
reuse it, but i can't be completely sure
The general rule is to declare the variables as late as possible (i.e. as close as possible to where you need them). But again, compilers can be very smart, and will optimize that away in most cases.
As for your specific example: it's always interesting to do a test. Chances are the compiler will optimize most of the differences away and might even generate the same code (or inline the whole function).
The best test is look at the generated assembly code. A lot can be learned from that.