可以在C++中比较原始内存

Is is possible to compare raw memory in C++?

本文关键字:比较 原始 内存 C++      更新时间:2023-10-16

我有几个固定长度的数组,想要比较它们。

struct Foo
{
    /// the data, not necessarily int and not necessarily length 32
    int val[32];
    /// simple way
    inline bool compare1(const NAME_CELL & rhs) const
    {
        for (unsigned int ui = 0; ui < 32; ++ui)
        {
            if (val[ui] != rhs.val[ui])
            {
                return false;
            }
        }
        return true;
    }
    /// compare memory directly instead of using a loop. Is this faster?
    inline bool compare2(const NAME_CELL & rhs) const
    {
        return memcmp(val, rhs.val, 32 * sizeof(int)) == 0;
    }
};
比较

1 是更慢、更快还是等于比较 2?有没有更快的方法?

除非你已经初始化val的元素,否则任何一种方法的行为在标准C++中都是未定义的

撇开这一点不谈,最好的办法是相信编译器会做出适当的优化。但是,如果您仍然有疑问,请(i(分析性能,(ii(检查生成的程序集,等等。