0

Possible Duplicate:
C++ STL: Which method of iteration over a STL container is better?
Efficiency of vector index access vs iterator access

Assuming an std::vector<int> named numbers, which of the following is faster?

for (vector<int>::iterator i = numbers.begin(); i != numbers.end(); i++)
  cout << *i;

or..

for (int i = 0; i < numbers.size(); i++)
  cout << numbers.at(i);

Which one is faster? Is there any significant difference?

Community
  • 1
  • 1
  • 2
    Not sure which is faster, but it's almost certainly insignificant. – Oleksi Apr 03 '12 at 00:06
  • 3
    cout is going to be the limiting factor here, by FAR. You won't make a benchmarking program that shows any difference in speed if you're printing them all to the terminal. – std''OrgnlDave Apr 03 '12 at 00:07
  • I ran a test similar to this on my system and found `at()` to be the slowest method (at does range checking), iterator being faster, and using an index and `[]` to be fastest. It probably depends on your system and compiler though. – kappamaki Apr 03 '12 at 00:13
  • Since `number.size()` returns an unsigned integral type, I would prefer `std::size_t i = 0;`. – Jesse Good Apr 03 '12 at 00:36

2 Answers2

1

Any difference will be dependent on the hardware and the compiler, so you'd have to measure. I'd expect no significant difference except on exotic hardware with a non-optimizing compiler.

And of course IO is likely to far outweigh the loop overhead.

bames53
  • 86,085
  • 15
  • 179
  • 244
1

Those two aren't even comparable. The former loops through each element, while the latter loops through while checking if the current index is valid (with at()). Take out the check and ask again:

for (/* Not an int! Unsigned type: */ std::size_t i = 0; i < numbers.size(); i++)
    cout << numbers[i];

Now they do the same thing. And now the question is a duplicate (#1 #2). To summarize: it doesn't matter.

Community
  • 1
  • 1
GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • Oh. `size_t` is preferable to `int` or `unsigned int`? I did not know that. Anyway, thanks! –  Apr 03 '12 at 00:48
  • 1
    @JonathanLingle size_t usually only matters for avoiding the compiler warning you get for comparing signed int vs. unsigned result of `.size()`. Using int also restricts the size of container you can work with, but usually int's range is sufficient. – bames53 Apr 03 '12 at 00:53