C++ 代码性能字符串比较 [英] C++ code performance strings compare

查看:65
本文介绍了C++ 代码性能字符串比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构数组(arrBoards),它有一些整数值、向量和字符串类型.我想比较结构中的某个字符串是否与输入的参数(字符串 p1)相等.

I have an array of struct (arrBoards) which has some integer values, vector and a string type. I want to compare if certain string in the struct is equal with entered parameter (string p1).

什么想法更快 - 用数组中的每个字符串元素检查输入字符串的方程,或者首先检查数组当前字符串元素中的 string.length() 是否大于 0,然后比较字符串.

What idea is faster - to check equation of input string with every string element inside an array, or firstly check if string.length() in current string element of the array greater than 0, then compare the strings.

if (p1.length())
{
    transform(p1.begin(), p1.end(), p1.begin(), ::tolower); //to lowercase
    for (int i=0; i<arrSize; i++) //check if string element already exists
        if ( rdPtr->arrBoards[i].sName == p1 )
        {
            */ some code */
            break;
        }
}

if (p1.length())
{
    transform(p1.begin(), p1.end(), p1.begin(), ::tolower); //to lowercase
    for (int i=0; i<arrSize; i++) //check if string element already exists
        if ( rdPtr->arrBoards[i].sName.length() ) //check length of the string in the element of the array
            if ( rdPtr->arrBoards[i].sName == p1 )
            {
                */ some code */
                break;
            }
}

我认为第二个想法更好,因为它不需要每次都计算名称,但我可能是错的,因为使用 if 会减慢代码速度.

I think the second idea is better because it don't need to calculate the name everytime, but I can be wrong because using if could slow down code.

感谢您的回答

推荐答案

我确信字符串类的比较运算符 (==) 已经足够优化了.就用它.

I'm sure the comparison operator (==) of the string class is already optimized enough. Just use it.

operator==(...) 基于短路比较返回一个布尔值

operator==(...) returns a bool based on a short-circuit comparison

return __x.size() == __n && _Traits::compare(__x.data(), __s, __n) == 0;

在调用 compare() 之前会检查字符串的大小,因此不需要进一步优化.

It checks the size of the strings before calling compare(), so, there is no need for further optimization.

永远记住软件工程的原则之一:KISS :P

Always remember one of the principles of Software Engineering: KISS :P

这篇关于C++ 代码性能字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆