1 / 9
raccy
  • 5,461
  • 1
  • 13
  • 38

newを使う理由の一つとして速度があるのではないでしょうか?

#include <chrono>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <iomanip>
#include <iostream>
#include <memory>

struct IntList {
    int val[100000];
};

auto benchmark(const std::function<void(int)> &func, const int count = 1)
{
    auto start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < count; ++i) func(i);
    auto end = std::chrono::high_resolution_clock::now();
    return std::chrono::duration_cast<std::chrono::nanoseconds>(end - start)
        .count();
}

int main()
{
    const int count = 100000;
    int n = 0;
    // stack
    auto stack_t = benchmark(
        [&n](int i) {
            IntList x;
            n += x.val[i];
            x.val[i] = i;
        },
        count);
    std::cout << " stack: " << std::setw(12) << stack_t << "ns" << std::endl;
    // malloc
    auto malloc_t = benchmark(
        [&n](int i) {
            auto p = static_cast<IntList *>(std::malloc(sizeof(IntList)));
            n += p->val[i];
            p->val[i] = i;
            std::free(p);
        },
        count);
    std::cout << "malloc: " << std::setw(12) << malloc_t << "ns" << std::endl;
    // new
    auto new_t = benchmark(
        [&n](int i) {
            auto p = new IntList;
            n += p->val[i];
            p->val[i] = i;
            delete p;
        },
        count);
    std::cout << "   new: " << std::setw(12) << new_t << "ns" << std::endl;
    // unique
    auto unique_t = benchmark(
        [&n](int i) {
            auto p = std::make_unique<IntList>();
            n += p->val[i];
            p->val[i] = i;
        },
        count);
    std::cout << "unique: " << std::setw(12) << unique_t << "ns" << std::endl;
    // shared
    auto shared_t = benchmark(
        [&n](int i) {
            auto p = std::make_shared<IntList>();
            n += p->val[i];
            p->val[i] = i;
        },
        count);
    std::cout << "shared: " << std::setw(12) << shared_t << "ns" << std::endl;
    std::cout << n << std::endl;
}

※ このコードはC++14向けです

上のコードをmacOS上でclang++ -O2 -std=c++14でコンパイルして実行すると下記の結果になりました。

 stack:       206556ns
malloc:       232281ns
   new:       220919ns
unique:   1373041817ns
shared:   1356433526ns

uniqueやsharedはラップされている分newよりも遅くなるようです。

raccy
  • 5,461
  • 1
  • 13
  • 38