vector<bool>性能测试

cpp 复制代码
#include <iostream>
#include <vector>
#include <sstream>
#include <numeric>
#include <string>
#include <unordered_map>
#include <queue>
#include <map>
using namespace std;


int main()
{
    clock_t t1, t2, t3;
    vector<bool> vb;
    vector<int> vi;
    vector<char> vc;

    t1 = clock();
    for (int i = 0; i < 1000; ++i)
    {
        for (int j = 0; j < 1000; ++j)
        {
            vb.push_back(true);
        }
    }
    t1 = clock() - t1;

    t2 = clock();
    for (int i = 0; i < 1000; ++i)
    {
        for (int j = 0; j < 1000; ++j)
        {
            vi.push_back(1);
        }
    }
    t2 = clock() - t2;

    t3 = clock();
    for (int i = 0; i < 1000; ++i)
    {
        for (int j = 0; j < 1000; ++j)
        {
            vc.push_back('a');
        }
    }
    t3 = clock() - t3;

    cout << "'vector<bool>::push_back(true)' 1000000 times cost: " << t1 << endl;
    cout << "'vector<int>::push_back(1)' 1000000 times cost: " << t2 << endl;
    cout << "'vector<char>::push_back('a')' 1000000 times cost: " << t3 << endl;

    t1 = clock();
    for (int i = 0; i < 1000; ++i)
    {
        for (int j = 0; j < 1000; ++j)
        {
            bool b = vb[j + 1000 * i];
        }
    }
    t1 = clock() - t1;

    t2 = clock();
    for (int i = 0; i < 1000; ++i)
    {
        for (int j = 0; j < 1000; ++j)
        {
            int b = vi[j + 1000 * i];
        }
    }
    t2 = clock() - t2;

    t3 = clock();
    for (int i = 0; i < 1000; ++i)
    {
        for (int j = 0; j < 1000; ++j)
        {
            char b = vc[j + 1000 * i];
        }
    }
    t3 = clock() - t3;

    cout << "'vector<bool>::operator[]' 1000000 times cost: " << t1 << endl;
    cout << "'vector<int>::operator[]' 1000000 times cost: " << t2 << endl;
    cout << "'vector<char>::operator[]' 1000000 times cost: " << t3 << endl;

    return 0;
}

测试结果

bash 复制代码
'vector<bool>::push_back(true)' 1000000 times cost: 4824
'vector<int>::push_back(1)' 1000000 times cost: 62
'vector<char>::push_back('a')' 1000000 times cost: 59
'vector<bool>::operator[]' 1000000 times cost: 312
'vector<int>::operator[]' 1000000 times cost: 5
'vector<char>::operator[]' 1000000 times cost: 6

原理:

vector<bool> 源码分析

相关推荐
沐知全栈开发2 小时前
HTML DOM 访问
开发语言
脑袋大大的3 小时前
JavaScript 性能优化实战:减少 DOM 操作引发的重排与重绘
开发语言·javascript·性能优化
二进制person4 小时前
Java SE--方法的使用
java·开发语言·算法
OneQ6664 小时前
C++讲解---创建日期类
开发语言·c++·算法
JoJo_Way5 小时前
LeetCode三数之和-js题解
javascript·算法·leetcode
码农不惑5 小时前
2025.06.27-14.44 C语言开发:Onvif(二)
c语言·开发语言
.30-06Springfield5 小时前
人工智能概念之七:集成学习思想(Bagging、Boosting、Stacking)
人工智能·算法·机器学习·集成学习
Coding小公仔7 小时前
C++ bitset 模板类
开发语言·c++
凌肖战7 小时前
力扣网C语言编程题:在数组中查找目标值位置之二分查找法
c语言·算法·leetcode
菜鸟看点7 小时前
自定义Cereal XML输出容器节点
c++·qt