-2

I have several arrays of fixed length and want to compare them.

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;
    }
};

Is compare1 slower, faster or equal to compare2? Is there an even faster way?

Fabian
  • 4,001
  • 4
  • 28
  • 59

1 Answers1

2

Unless you've initialised the elements of val then the behaviour of either method is undefined in Standard C++.

Setting that aside, you're best bet is to trust the compiler to make the appropriate optimisations. But if you're still in doubt, (i) profile the performance, (ii) check the generated assembly, &c.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Re initialisation: why is the behaviour undefined? The contents of val would be, but the behaviour? – James May 08 '17 at 08:37
  • 1
    `int` could contain a trap representation. An `unsigned char` array would be fine. See http://stackoverflow.com/questions/11962457/why-is-using-an-uninitialized-variable-undefined-behavior-in-c. Granted, it's tagged C, but a good starting point. – Bathsheba May 08 '17 at 08:38
  • Of course you have to initialize the Foos before comparing them. No need to mention this. – Fabian May 08 '17 at 09:15