dimanche 29 août 2021

Is unique_ptr faster than raw pointer? C++

I was experimenting with the benchmarking here and found weird results.
Apparently creating and deleting raw pointer is slower (according to my measurements of course) than creating unique_ptr, how is this possible?

struct deleter 
{
    template<typename T>
    void operator()(T* ptr) 
    {
        delete ptr;
    }
};

void BM_rawPtr(benchmark::State& state)
{
    deleter d;
    for (auto _ : state)
    {
        int* p = new int(0);
        d(p);
    }
    state.SetItemsProcessed(state.iterations());
}


void BM_uniquePtr(benchmark::State& state)
{
    deleter d;
    for (auto _ : state)
    {
        std::unique_ptr<int, deleter> ptr(new int(0), d);
    }
    state.SetItemsProcessed(state.iterations());
}

BENCHMARK(BM_rawPtr);
BENCHMARK(BM_uniquePtr);
BENCHMARK_MAIN();

This gave me weird results:

enter image description here

I don't want to claim nonsense like "unique_ptr is faster than raw pointer".
Clearly I have missed some point here, does this ring a bell to anyone?

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire