c++性能优化

文章探讨了如何使用C++优化std::string处理,包括避免临时字符串,减少内存重分配,使用迭代器,以及利用字符数组来过滤并移除ASCII值小于0x20的控制字符。同时,提到了更好的算法选择和避免性能下降的编程实践。
摘要由CSDN通过智能技术生成
std::string remove_ctrl(std::string s) {
    std::string result;  
    for (int i=0; i<s.length(); ++i) {
    if(s[i] >= 0x20)
        result = result + s[i];
    }
    return result;
}

// 使用复合赋值操作    避免临时字符串
result = result + s[i]; // result += s[i];
// 通过预留存储空间    减少内存的重新分配
std::string result;  
result.reserve(s.length());
for (int i=0; i<s.length(); ++i) {
// 消除对参数字符串的复制
std::string remove_ctrl_ref_args(std::string const& s) // 要解引用成指针
// 使用迭代器消除指针解引
for (auto it=s.begin(),end=s.end(); it != end; ++it) {
    if (*it >= 0x20)
    result += *it;
}
// 消除对返回的字符串的复制
void remove_ctrl_ref_result_it (
    std::string& result,
    std::string const& s)
{
    result.clear();
// 用字符数组代替字符串
void remove_ctrl_cstrings(char* destp, char const* srcp, size_t size) {
for (size_t i=0; i<size; ++i) {
if (srcp[i] >= 0x20)
*destp++ = srcp[i];

// 更好的算法,提前结束for break
// substr生成字串
// 如果std::stringstream 是用std::string 实现的,那么它在性能上永远不能胜过std::string。
它的优点在于可以防止某些降低程序性能的编程实践

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值