std::vector efficiency

This is a discussion on std::vector efficiency within the C++ Programming forums, part of the General Programming Boards category; I have a vector<some struct> obj. Question: which is more efficient or are both methods about the same? Code: struct ...

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267

    std::vector efficiency

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

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,339
    Do you mean this:
    Code:
    mystruct& s = obj[i];
    It is the same as asking which of these is more efficient:
    Code:
    int i = 10;
     
    ++i;
     
    // or
     
    int& j = i;
    ++j;
    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
    Posts
    116
    >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.

    Cheers!

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21