在字符串中查找子串的两种方法速度对比

背景:从ini配置文件中读取到的字符串,在其中查找某一子串是否存在

第一种方法:将读取到的字符串分割后以元素形式存在set集合中,使用count()函数查找

第二种方法:直接将字符串保存为string,用string.find()查找

代码:

#include 
#include 
#include 
#include 

using namespace std;


string g_subscribeSymbol;
static set g_symbols;
LARGE_INTEGER startTime, endTime;

struct st_symbol_id
{
    long long   m_i_symbol_id:48;
};

// 字符串分割
void split_string(const char* pStr, vector& vecString, char boundary)
{
    vecString.clear();
    string str = "";

    while (*pStr) {
        if (boundary == *pStr) {
            vecString.push_back(str);
            str = "";
            while (*pStr == boundary) {
                ++pStr;
            }
        } else {
            str.append(1, *pStr);
            ++pStr;
        }
    }
    if (str.length() > 0) {
        vecString.push_back(str);
    }
}

// 字符串存储
void push_filter_symbol(const char* str_symbol)
{
    g_symbols.insert(((st_symbol_id*)(str_symbol))->m_i_symbol_id);
}

int main()
{
    g_subscribeSymbol = "600000,600031,600053,600056,600150,600198,600199,600305,600516,600536,600999,601939,603259,603712,688005,688009,688016,688379,688519,688568,000016,000132,000009,510050,000001,000156,000338,000402,000547,000651,000776,000880,000930,002925,002828,002456,002594,002670,002797,300001,300059,300202,300349,300433,300527,300688,300750,399001,399006";

    vector vec_str;
    split_string(g_subscribeSymbol.c_str(), vec_str, ','); // 拆分
    for (size_t i = 0; i < vec_str.size(); i++) {
        push_filter_symbol(vec_str[i].c_str()); // 写入set
    }

    string symbol = "399006";
    QueryPerformanceCounter(&startTime);
    if (g_symbols.count(((st_symbol_id*)(symbol.c_str()))->m_i_symbol_id) != 0)
        cout << "found" << endl;
    QueryPerformanceCounter(&endTime);
    cout << "startTime: " << startTime.QuadPart << " endTime: " << endTime.QuadPart << " duration: " << endTime.QuadPart - startTime.QuadPart << endl;

    QueryPerformanceCounter(&startTime);
    if (g_subscribeSymbol.find(symbol) != string::npos)
        cout << "found" << endl;
    QueryPerformanceCounter(&endTime);
    cout << "startTime: " << startTime.QuadPart << " endTime: " << endTime.QuadPart << " duration: " << endTime.QuadPart - startTime.QuadPart << endl;

    system("pause");
    return 0;
}

运行结果


image.png

结论:string查找快

你可能感兴趣的:(在字符串中查找子串的两种方法速度对比)