![](/img/trans.png)
[英]constexpr const char * vs constexpr 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*`?
int
& int
VS a const char*
& const char*
的inline constexpr
function 的性能是否存在理論上的差異? 示例 1( int
等於int
)
struct some_struct {
int m_type;
...
inline constexpr
void somefunc() {
if (m_type == 0) {
...
} else if (m_type == 1) {
...
}
}
};
示例 2( const char*
等於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")) {
...
}
}
};
正如@RichardCritten 指出的那樣, strcmp
不是constexpr
function。 雖然在我的實際代碼中,我有一個自定義strcmp
function,它是一個constexpr
function。
Consexpr 函數僅在需要時在編譯時計算,我的意思是在常量表達式中。
所以在常量表達式中,運行時的性能沒有差異(編譯時間可能不同)。
在非常量表達式中,函數在運行時與任何常規函數一樣計算(使用 as-if 規則,優化器可能會優化並返回編譯時計算的結果,在這方面constexpr
可能是編譯器的提示)。
這取決於。
一切都可以在編譯時完成嗎? 不必要。 如果是,那么運行時當然不會有任何區別。
對於運行時? 在某些機器上,根據架構, int
和char*
的比較可能是相同的。
這可以通過查看匯編代碼來找到。 盡管如此,一些 CPU 內部程序也會產生影響。
但是,將整數類型與 C 風格的字符串進行比較很少有相同的性能,因為對於一個字符串,需要比較許多字節。 在這里,現代 CPU 架構和匯編指令也可能有所幫助。
我對您的問題(似乎是xy 問題)的回答是:
很可能存在差異,但這取決於。 . .
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.