乍一看,仅对[]
运算符而言,它比原始指针慢大约5倍,如以下代码所示,该代码使用gcc -lstdc++ -std=c++14 -O0
并输出了以下结果:
malloc []: 414252610
unique [] is: 2062494135
uq get [] is: 238801500
uq.get()[] is: 1505169542
new is: 241049490
我开始学习c ++,我已经想到了这一点:您总是需要知道自己在做什么,并花更多的时间来了解其他人在c ++中所做的事情。
编辑
根据@Mohan Kumar的方法,我提供了更多详细信息。gcc版本是7.4.0 (Ubuntu 7.4.0-1ubuntu1~14.04~ppa1)
,使用时获得了以上结果-O0
,但是,当我使用'-O2'标志时,得到了以下结果:
malloc []: 223
unique [] is: 105586217
uq get [] is: 71129461
uq.get()[] is: 69246502
new is: 9683
然后转移到clang version 3.9.0
,-O0
是:
malloc []: 409765889
unique [] is: 1351714189
uq get [] is: 256090843
uq.get()[] is: 1026846852
new is: 255421307
-O2
是:
malloc []: 150
unique [] is: 124
uq get [] is: 83
uq.get()[] is: 83
new is: 54
lang的结果-O2
是惊人的。
#include <memory>
#include <iostream>
#include <chrono>
#include <thread>
uint32_t n = 100000000;
void t_m(void){
auto a = (char*) malloc(n*sizeof(char));
for(uint32_t i=0; i<n; i++) a[i] = 'A';
}
void t_u(void){
auto a = std::unique_ptr<char[]>(new char[n]);
for(uint32_t i=0; i<n; i++) a[i] = 'A';
}
void t_u2(void){
auto a = std::unique_ptr<char[]>(new char[n]);
auto tmp = a.get();
for(uint32_t i=0; i<n; i++) tmp[i] = 'A';
}
void t_u3(void){
auto a = std::unique_ptr<char[]>(new char[n]);
for(uint32_t i=0; i<n; i++) a.get()[i] = 'A';
}
void t_new(void){
auto a = new char[n];
for(uint32_t i=0; i<n; i++) a[i] = 'A';
}
int main(){
auto start = std::chrono::high_resolution_clock::now();
t_m();
auto end1 = std::chrono::high_resolution_clock::now();
t_u();
auto end2 = std::chrono::high_resolution_clock::now();
t_u2();
auto end3 = std::chrono::high_resolution_clock::now();
t_u3();
auto end4 = std::chrono::high_resolution_clock::now();
t_new();
auto end5 = std::chrono::high_resolution_clock::now();
std::cout << "malloc []: " << (end1 - start).count() << std::endl;
std::cout << "unique [] is: " << (end2 - end1).count() << std::endl;
std::cout << "uq get [] is: " << (end3 - end2).count() << std::endl;
std::cout << "uq.get()[] is: " << (end4 - end3).count() << std::endl;
std::cout << "new is: " << (end5 - end4).count() << std::endl;
}