placement newの速度
普通のnewと、placement newがどのくらい速度が違うのかを比較してみました。
#include "stdafx.h" #include <new> #include "TIME.H" class MyClass { public: MyClass() : m_value(0), m_dbl(0.0) { } MyClass(int value) : m_value(value), m_dbl(0.0) { } public: int m_value; double m_dbl; }; int _tmain(int argc, _TCHAR* argv[]) { #define MAX_ELEMENTS 1000000 clock_t start, end; // 通常のnew start = clock(); for (int i=0; i<MAX_ELEMENTS; i++) { MyClass *pObj = new MyClass(100); } end = clock(); printf("new:\t\t%.3f秒\n", (double)(end-start)/CLOCKS_PER_SEC); // placement new int size = sizeof(MyClass); start = clock(); char *pool = (char*)new char[size * MAX_ELEMENTS]; for (int i=0; i<MAX_ELEMENTS; i++) { MyClass * pObj = new (pool + i*size) MyClass(100); } end = clock(); printf("placement new:\t%.3f秒\n", (double)(end-start)/CLOCKS_PER_SEC); return 0; }
結果
new: 0.312秒 placement new: 0.016秒
クラスのサイズを変えるとまた違うので、この数字を鵜呑みにはできません。