Phil CK

Quick Bench Malloc vs New

Last updated on

I just found Quick Bench and have been playing around with it. It seems quite useful on the surface.

I wrote this test already kinda knowing what the result was.

results

Full Code

#include <stdlib.h>

static void malloc_bench(benchmark::State& state) {
  for (auto _ : state) {
    char *addr = (char*)malloc(128);
    free(addr);
    benchmark::DoNotOptimize(addr);
  }
}
BENCHMARK(malloc_bench);

static void new_bench_arr(benchmark::State& state) {
  for (auto _ : state) {
    char *addr = new char[128];
    delete[] addr;
    benchmark::DoNotOptimize(addr);
  }
}
BENCHMARK(new_bench_arr);

static void new_bench(benchmark::State& state) {
  for (auto _ : state) {
    struct block {
      char data[128];
    };
    block *addr = new block;
    delete addr;
    benchmark::DoNotOptimize(addr);
  }
}
BENCHMARK(new_bench);

static void new_place(benchmark::State& state) {
  char bdata[256];

  for (auto _ : state) {
    struct block {
      char data[128];
    };
    block *addr = new((void*)bdata) block;
    benchmark::DoNotOptimize(addr);
  }
}
BENCHMARK(new_place);