c++ string strcpy赋值性能测试, strcpy至少快40倍以上

该代码段对比了C++中使用`std::string`对象和字符数组进行多次赋值操作的性能差异。在1000000次循环中,`f()`函数反复修改`std::string`对象,而`f2()`函数则用`strcpy`函数更新字符数组。结果显示,`f2()`(字符数组)在执行时间上优于`f()`(`std::string`)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

测试代码:


#include "stdafx.h"
#include <string>
#include <time.h>
#include <iostream>

using namespace std;

string str = "123";
std::string& f()
{
	str = "123";
	str = "123";
	str = "123";
	str = "123";
	str = "123";
	str = "123";
	str = "123";
	str = "123";
	str = "123";
	str = "123";
	return str;
}

char buf[32];
char * f2()
{
	strcpy(buf, "123");
	strcpy(buf, "123");
	strcpy(buf, "123");
	strcpy(buf, "123");
	strcpy(buf, "123");
	strcpy(buf, "123");
	strcpy(buf, "123");
	strcpy(buf, "123");
	strcpy(buf, "123");
	strcpy(buf, "123");
	return buf;
}

int main()
{
	int num = 1000000;
	
	cout << clock() << endl;
	for (int i = 0; i < num; ++i)
	{
		f();
	}
	cout << clock() << endl;
	for (int i = 0; i < num; ++i)
	{
		f2();
	}
	cout << clock() << endl;

	string i;
	cin >> i;
	return 0;
}


输出结果:

126
4065
4108

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值