473,769 Members | 4,909 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

vector performance: iterator versus subscripting

Is there any difference, performance-wise, accessing elements of a
vector using iterators or the subscript operator?

In other words, say I have a vector of strings:

vector<string> strvec;

After some processing, the vector has a very large (>50,000) number of
elements. Is there any performance difference in the following methods
of vector access?

vector<string>: :iterator ii;
for (ii=strvec.begi n(); ii!=strvec.end( ); ++ii) {
// do stuff with *ii
}

Alternative:

unsigned long i;
for (i=0; i<strvec.size() ; i++) {
// do stuff with strvec[i]
}

I did make a quick and dirty test of this: I read in about 5 MB worth of
strings (the strings were random numbers generated in another program by
rand()) into a vector. I then output those strings to files, once using
iterators and once using vector subscripting. There was no difference
in runtime.

That test obviously isn't at all complete, but I was hoping some
knowledgeable folks had the answer(s) :)

Thanks,
Matt
email at: http://raw-sewage.net/index.php?file=email

Jul 22 '05 #1
4 4326
"Matt Garman" <ga****@raw-sewage.bogus> wrote in message
news:sl******** ***********@new s-proxy.cso.uiuc. edu...
| Is there any difference, performance-wise, accessing elements of a
| vector using iterators or the subscript operator?
Not a predictable difference, and most likely a negligible one.
....
| After some processing, the vector has a very large (>50,000) number of
| elements. Is there any performance difference in the following methods
| of vector access?
|
| vector<string>: :iterator ii;
| for (ii=strvec.begi n(); ii!=strvec.end( ); ++ii) {
| // do stuff with *ii
| }
....
| unsigned long i;
| for (i=0; i<strvec.size() ; i++) {
| // do stuff with strvec[i]
| }
Other factors are likely to affect performance much more than
using indexing vs. iterators on std::vector.
For example, loading the value of strvec.end() or strvec.size() into
a local variable instead of calling the function at every iteration is
likely to make a more important (albeit small) performance difference.

Ideally, if all functions of std::vector are inlined, a compiler could
generate optimal code for both loop implementations .

An advantage of iterators is that it that they can be more flexible
if you later need to work with a different container type,
standard algorithms, or a subrange of the container.

So I would personally write the loop as:
typedef vector<string>: :iterator It;
It end = strvec.end();
for( It scan = strvec.begin() ; scan != end ; ++scan )
{
string const& str = *scan;
... do stuff with str ...
}

Or, better, use a function object and the std::for_each() algorithm...

| I did make a quick and dirty test of this: I read in about 5 MB worth of
| strings (the strings were random numbers generated in another program by
| rand()) into a vector. I then output those strings to files, once using
| iterators and once using vector subscripting. There was no difference
| in runtime.
The file I/O and memory allocations would in any case have outweighed
the performance difference between the two loop implementations .
I hope this helped,
Ivan
--
http://ivan.vecerina.com
Jul 22 '05 #2
> For example, loading the value of strvec.end() or strvec.size() into
a local variable instead of calling the function at every iteration is
likely to make a more important (albeit small) performance difference.


It is possible that the size or the last element of the vector changes
during the loop. Wouldn't that be a problem if .end() resp. .size() are
saved to local variables before?

Jul 22 '05 #3

"Harald Grossauer" <ha************ **@uibk.ac.at> skrev i en meddelelse
news:3f******@s ia.uibk.ac.at.. .
For example, loading the value of strvec.end() or strvec.size() into
a local variable instead of calling the function at every iteration is
likely to make a more important (albeit small) performance difference.


It is possible that the size or the last element of the vector changes
during the loop. Wouldn't that be a problem if .end() resp. .size() are
saved to local variables before?


Yes. In this case, you can not store the end() before the loop starts.
But do not be that obsessed with performance. Write the code, and if it runs
to slowly profile it and eliminate bottlenecks.

Kind regards
Peter
Jul 22 '05 #4
"Peter Koch Larsen" <pk*@mailme.d k> wrote in message
news:3f******** *************** @dread11.news.t ele.dk...
| "Harald Grossauer" <ha************ **@uibk.ac.at> skrev i en meddelelse
| news:3f******@s ia.uibk.ac.at.. .
| > > For example, loading the value of strvec.end() or strvec.size() into
| > > a local variable instead of calling the function at every iteration is
| > > likely to make a more important (albeit small) performance difference.
| >
| > It is possible that the size or the last element of the vector changes
| > during the loop. Wouldn't that be a problem if .end() resp. .size() are
| > saved to local variables before?
| >
|
| Yes. In this case, you can not store the end() before the loop starts.
| But do not be that obsessed with performance. Write the code, and if it
runs
| to slowly profile it and eliminate bottlenecks.

Ah, the fine line between "premature optimization"
and "avoiding unnecessary pessimization" ;-)

In this case, I would consider it a matter of style (I have a
macro in my editor to automatically generate a for-each like loop
with a stored end bound).

But of course, as I had mentioned in my first reply, using for_each()
is a first choice if a functor can be provided easily.

Regards,
Ivan
--
http://ivan.vecerina.com
Jul 22 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
5027
by: Jim West | last post by:
I'm curious why I might be getting such a large performance difference between using a map iterator and a vector iterator. This is a computational electromagnetics code where I have to separate points in space that arrive randomly into groupings based on (x, y, z) dimensions, so I use std::map to do that. Once the sorting is done I need to find the interactions between groups, so I've been using iterators to step through the map. As a...
11
8880
by: Steve | last post by:
Hi, I'm using a std::vector to store a list of user defined objects. The vector may have well over 1000 elements, and I'm suffering a performance hit. If I use push_back I get a much worse perfomance than if I first define the vector of a given size, then write to the elements with myvec = However, I'm currently thinking that it isn't feasible to obtain the vector size, so really need to resize the vector dynamically as I go. Is...
29
3975
by: Hagen | last post by:
Hello, in a recent thread "speed of vector vs array" I read about the problem of the slow acces by addressing vector elements by indexing, unfortunately I see no workaround in my case. My case: class A {
19
3363
by: daniel | last post by:
1) is C++ smart enough to automatically use "bits" for bool or will a bool have the size of a charcter (byte). 2) The index of a vector is it an integer (4 byte) or a "long long" with 8 bytes or something else? I ask because I want to use vector<bool> with a few billion entries exceeding the int32 range for indexing and I want to use as few memory as possible for the whole
13
20152
by: zaineb | last post by:
Hi, This is a follow-up of sort of this thread: http://groups.google.com/group/comp.lang.c++/browse_thread/thread/de12af6539e0d645/662cab752779f1fa?lnk=st&q=c%2B%2B+vector+vs+map&rnum=1&hl=en#662cab752779f1fa I've been chewing on this problem for a while. When I came across the above thread, I figured that maybe other members have a better idea on how to approach this. I'm currently trying to decide between which one of maps or...
23
6545
by: Sanjay Kumar | last post by:
Folks, I am getting back into C++ after a long time and I have this simple question: How do pyou ass a STL container like say a vector or a map (to and from a function) ? function: vector<string> tokenize(string s){
6
6830
by: zl2k | last post by:
hi, there I am using a big, sparse binary array (size of 256^3). The size may be changed in run time. I first thought about using the bitset but found its size is unchangeable. If I use the vector<bool>, does each element takes 4 bytes instead of 1 bit? I am using gcc3.4.4. There is a bit_vector which is kind of old so I wont use that. Any other choices? Thanks ahead. zl2k
2
2352
by: ma740988 | last post by:
typedef std::vector < std::complex < double > > complex_vec_type; // option1 int main() { complex_vec_type cc ( 24000 ); complex_vec_type dd ( &cc, &cc ); } versus
6
1417
by: Michael | last post by:
Hi, I am new to C++ and have run into the following problem. I have written some functions which return a vector e.g vector<doublemyfunction(double arg1,.......,.....) { }
0
9586
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10043
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9990
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8869
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7406
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5298
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3956
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.