Salchipapas
Salchipapas

Reputation: 118

Does std::string allocated memory interfere with performance?

I have a Stock class in which one of the members is a string which maximum length will be at most 6 chars (stock tickers in the NASDAQ cannot be longer than 5 characters plus the added Q if they were to go bankrupt). However, since the NASDAQ alone has about 3500 stocks I would like to use as little data as possible when making a Stock object. std::string allocates more space than I need for its contents and I am trying to reduce memory consumption. Would the extra allocated memory that std::string uses affect the performance of my program at all?

In the following code it shows that the member variable symbol has a size of 15 even though there are only 4 chars in it. Can I restrict the string size to 6 bytes using str.reserve inside the class before the initialization, or should I instantiate the object then call symbol.resize(6) to ensure there are only 6 bytes being used?

#include <iostream>
#include <string>

using namespace std;


class Stock
{
public:
    Stock(string s, double o, double c, unsigned int v)
     : symbol(s), open(o), close(c), volume(v) {};
    ~Stock() = default;
    string symbol;
    double open;
    double close;
    unsigned int volume; 
};

int main() {
    Stock AAPL("AAPL", 267.48, 270.71, 26547493);
    cout << AAPL.symbol.capacity() << endl;
    cout << AAPL.symbol.size() << endl;

    return 0;
}

From reading the answer to this question STD::string as a Member Parameter for Dynamically Allocated Objects it seems that this extra allocated space that std::string uses should not interfere at all with the memory of my program, but I am not 100% sure and I would prefer if someone could corroborate my assumption.

Upvotes: 1

Views: 225

Answers (1)

Build Succeeded
Build Succeeded

Reputation: 1150

I think, Best way is a combination of type definition. Use char ticker[6+1] and if you need to parse the data or process it uses the std::string_view.

Upvotes: 1

Related Questions