Home > Software engineering >  Is iterating inside a vector slower than accessing indices with a for loop?
Is iterating inside a vector slower than accessing indices with a for loop?

Time:02-03

Is iterating through a vector of integers slower than accessing the indices using a loop? Here's what I mean:

std::vector<int> nums = {1, 2, 3, 4, 5};
for (int num : nums) {
    std::cout << num;
}

for (int i = 0; i < nums; i  ) {
    std::cout << nums[i] << "\n";
}

Which one would be faster, which one uses more memory?

I'm just wondering which one is better performance-wise.

CodePudding user response:

There is ultimately no way to know for sure apart from trying it and measuring it. There are always unexpected things that can happen that can affect the performance, so performance predictions on this level of detail are not always useful. But I would expect that your compiler is smart enough to produce the same code.

There is a chance the first one is slightly faster because it doesn't call nums.size() on every iteration. If the compiler can't be sure that nums.size() doesn't change, it might actually check the size again, on every iteration. The : syntax calculates the start and end of the vector before it runs the loop.

I suppose you meant i < nums.size() in the second one.

CodePudding user response:

I don't know about memory, but

for (int i = 0; i < nums; i  ) {
    std::cout << nums[i] << "\n";
}

is significantly faster.

  •  Tags:  
  • c
  • Related