字符串连接比较(std::unique_ptr实现)
比较代码之间可能相差大,可是速度相差很大,而且目的在于测试unique_ptr使用...;
C/C++:
1 #include <iostream> 2 3 4 std::unique_ptr<char[]> strcat_test(std::initializer_list<const char *> li) 5 { 6 std::size_t size{}; 7 std::for_each(li.begin(), li.end(), [&size](const char *str) 8 { size += strlen(str); }); 9 10 std::unique_ptr<char[]> uniq_char(new char[size + 1]); 11 char *temp = uniq_char.get(); 12 13 std::for_each(li.begin(), li.end(), [&temp](const char *str) 14 { 15 std::size_t size=strlen(str); 16 memcpy(temp, str, size); 17 temp += size; 18 }); 19 20 temp[size] = '\0'; 21 22 return uniq_char; 23 } 24 25 26 int main() 27 { 28 29 std::size_t times=10000; 30 31 32 std::clock_t start=0,end=0; 33 34 start=clock(); 35 for(int i=0;i<times;i++) 36 { 37 strcat_test({"Hello"," World","dasd","asdasdasd","adadad"}); 38 } 39 end=clock(); 40 41 std::cout<<(double(end-start)/CLOCKS_PER_SEC)<<std::endl; 42 43 44 start=clock(); 45 for(int i=0;i<times;i++) 46 { 47 char str[11]{"Hello"}; 48 strcat(str,"World"); 49 } 50 end=clock(); 51 52 std::cout<<(double(end-start)/CLOCKS_PER_SEC)<<std::endl; 53 54 55 56 return 0; 57 }
运行结果: