What is fastest?

C

carl

What is fastest, indexing or iterating a std::vector:


std::vector<std::string> container;
// Add 100000 strings to container

std::vector<std::string>::iterator it = container.begin()
while (it != container.end()) {
std::string str = *it;
// do something with str
it++;
}


or

int size = container.size();
for (int i=0; i< size; i++) {
std::string str = container;
// do something with str
}

On this page:

http://stackoverflow.com/questions/...-an-stl-vector-with-vectoriterator-or-with-at


there are some different opinions, but what are your experinces?
 
V

Victor Bazarov

carl said:
What is fastest, indexing or iterating a std::vector:


std::vector<std::string> container;
// Add 100000 strings to container

std::vector<std::string>::iterator it = container.begin()
while (it != container.end()) {
std::string str = *it;
// do something with str
it++;
}


or

int size = container.size();
for (int i=0; i< size; i++) {
std::string str = container;
// do something with str
}

On this page:

http://stackoverflow.com/questions/...-an-stl-vector-with-vectoriterator-or-with-at



there are some different opinions, but what are your experinces?


In my experience, those things are compiler-specific, system-specific,
and cannot be theorised upon. They need to be measured.

V
 
B

Bo Persson

carl said:
What is fastest, indexing or iterating a std::vector:


std::vector<std::string> container;
// Add 100000 strings to container

std::vector<std::string>::iterator it = container.begin()
while (it != container.end()) {
std::string str = *it;
// do something with str
it++;
}


or

int size = container.size();
for (int i=0; i< size; i++) {
std::string str = container;
// do something with str
}

On this page:

http://stackoverflow.com/questions/...-an-stl-vector-with-vectoriterator-or-with-at


there are some different opinions, but what are your experinces?


I think that "different opinions" is the correct result :)

It varies some, but the difference is VERY small. The "do something
with str" is highly likely to dominate the timing anyway.


Bo Persson
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,156
Messages
2,570,878
Members
47,408
Latest member
AlenaRay88

Latest Threads

Top