gpt4 book ai didi

c++ - 空/空字符串检查 : CPU overhead

转载 作者:太空宇宙 更新时间:2023-11-04 16:17:16 26 4
gpt4 key购买 nike

我有这个函数可以在 OpenGL 中打印二维文本

void Text2D::printText(const BMfont &font, const char *text, const PenList &pen_list);

我有几个应用程序(游戏)经常使用它,但我从来没有向它传递空字符串但现在。我使用的大部分 stringstd::string::c_str()

此外,我还有这些用于空值检查(或空字符串检查)的变体。

    if (text[0] == '\0') return; // # 1
if (text == '\0') return; // # 2
if (text == nullptr) return; // # 3

这将是调用函数 Text2D::printText() 时要执行的第一条指令

除了 # 1 之外,所有这些检查都会导致 CPU 使用率大约为 50%。我很确定它是,这对我来说很奇怪。

这三者有什么区别?我认为 # 1# 2 是相同的并且我认为 # 3 会将 nullptr 转换为 '\0'?为什么 #2#3 占用过多的 CPU 使用率?检查空 C 字符串 的正确且安全的方法是什么?

最佳答案

没有办法 (1)(单独检查,之后不执行)可以比 (2) 和 (3) 更快。逻辑上认为跟随指针比仅仅检查地址值需要更多的周期。

例如检查为 x86 生成的代码。

if (text == '\0') return -1;  //   # 2

01028C6E cmp dword ptr [文本],0
01028C72 jne printText+29h (01028C79h)
01028C74 或 eax,0FFFFFFFFh
01028C77 jmp 打印文本+4Bh (01028C9Bh)

if (text == nullptr) return 0; // # 3

01028C79 cmp dword ptr [文本],0
01028C7D jne printText+33h (01028C83h)
01028C7F xor eax,eax
01028C81 jmp 打印文本+4Bh (01028C9Bh)

  if (text[0] == '\0') return 1; // # 1

01028C83 mov eax,1
01028C88 imul eax,eax,0
01028C8B mov ecx,dword ptr [文本]
01028C8E movsx edx,byte ptr [ecx+eax]
01028C92 测试 edx,edx
01028C94 jne printText+4Bh (01028C9Bh)
01028C96 mov eax,1

请注意,您不应该在不检查指针本身的情况下取消对指针的引用。

关于c++ - 空/空字符串检查 : CPU overhead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21421791/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com