简体   繁体   中英

Is there any theoretical difference in performance in an inline constexpr function that compares an `int` & `int` VS a `const char* & `const char*`?

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.

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).

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 xy problem , is:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM