C++ string 字符串和C字符串查找效率对比测试

文章通过一个简单的字符串查找功能实现对比,展示了C风格的字符串处理函数相对于STL中的find方法在特定条件下可能具有大约10倍的性能优势。测试代码中,f()函数使用了STL的find,而f2()函数使用了C风格的字符串遍历。经过1000000次查找操作,C风格的f2()函数执行时间显著少于STL的f()函数。

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

结论:

C风格要快10倍左右。

代码:


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

using namespace std;

string str = "123456789";
int f()
{
	return str.find("678");
}

char buf[32];
int f2(const char *p = "678")
{
	for (int i = 0; i < 32; ++i)
	{
		int j = i;
		int k = 0;
		while (buf[j] == p[k])
		{
			++j;
			k++;
		}
		if (buf[j] == 0)
		{
			return -1;
		}
		if (p[k] == 0)
		{
			return i;
		}
	}
	return -1;
}

int main()
{
	int num = 1000000;
	strcpy(buf, "123456789");


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

	cout << f() << endl;
	cout << f2() << endl;

	bool b = (-1 == std::string::npos);
	cout << b << endl;
	string i;
	cin >> i;
	return 0;
}


输出结果:

67
2098
2410
5
5
1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值