Home > database >  Is there any theoretical difference in performance in an inline constexpr function that compares an
Is there any theoretical difference in performance in an inline constexpr function that compares an

Time:08-28

Is there any theoretical difference in performance in an inline constexpr function that compares an int & int VS a const char* & const char*, when optimization is enabled?

Example 1 (int equals int)

struct some_struct {
    int m_type;
    ...
    inline constexpr
    void somefunc() {
        if (m_type == 0) {
            ...
        } else if (m_type == 1) {
            ...
        }
    }
};

Example 2 (const char* equals const char*)

struct some_struct {
    const char* m_type;
    ...
    inline constexpr
    void somefunc() {
        if (strcmp(m_type, "some_str_1")) {
            ...
        } else if (strcmp(m_type, "some_str_2")) {
            ...
        }
    }
};

Edit:

As @RichardCritten pointed out, strcmp is not a constexpr function. Though in my actual code I have a custom strcmp function that is a constexpr function.

CodePudding user response:

Constexpr functions are computed at compile-time only when required, I mean in constant expression.

So in constant expression, there are no difference in performance at runtime (compilation time might differ).

In non-constant expression, functions are computed at runtime as any regular functions (With as-if rule, optimizer might optimize and return a result computed at compilation, constexpr might be a hint for compiler in that regards).

CodePudding user response:

It depends.

Can everytghing be done at compile time? Not necessarily. If yes, then of course there will be no difference in runtime.

And for runtime? On some machines and depending on the arictecture a comparison of an int and char* can be the same.

This can be found out by looking at the assembler code. Still, some CPU internal procedures will also have an impact.

But, comparing an integral type with a C-style character string will rarely have the same performance, because for a string many bytes need to be compared. Also here modern CPU architecury and assembler instructions may help.

My answer to your question, which seemms to be an x y problem, is:

Most likely there is a difference, but it depends . . .

  • Related