Thread: std::vector efficiency

  1. #1
    Registered User
    Join Date
    Aug 2005

    std::vector efficiency

    I have a vector<some struct> obj. Question: which is more efficient or are both methods about the same?
    struct mystruct
       long quantity;
       ... // other stuff here
    vector<mystruct> obj;
    int i; // assum its already set to a valid number
    or this
    mystruct s& obj[i];

  2. #2
    Registered User
    Join Date
    Jan 2005
    Do you mean this:
    mystruct& s = obj[i];
    It is the same as asking which of these is more efficient:
    int i = 10;
    // or
    int& j = i;
    If you have a reason to do the second one like for better clarity, readability, etc, then do it. The extra reference variable shouldn't make a noticable difference. If you don't have a preference, then use the first to avoid the extra variable.

  3. #3
    Rabble Rouser Slacker's Avatar
    Join Date
    Dec 2005
    >which is more efficient or are both methods about the same?
    It shouldn't matter since just about any standard optimization will outweigh the difference between the two examples you gave. But since you didn't ask which you should use, only which is more efficient, I would guess the first because it avoids an initialization operation. I'm guessing only because it's really hard to tell what's faster just by looking at the code. A better way to figure it out is to use a profiler.


Popular pages Recent additions subscribe to a feed