Why is there a performance warning on cast pointer to bool?

前端 未结 6 1945
花落未央
花落未央 2020-12-09 01:14

Extends.

I thought I was being cool when I did something like:

bool hasParent()
{
  return this->parentNode ;
}

Even with a (bool) cast, the

6条回答
  •  清歌不尽
    2020-12-09 02:01

    Why is that a performance warning?

    The compiler is turning this:

    bool hasParent()
    {
      return this->parentNode;
    }
    

    into:

    bool hasParent()
    {
      return this->parentNode != 0;
    }
    

    This takes about one clock cycle more than you might expect from looking at the code. It's an insignificant performance difference.

    I think it's better to write out the != 0 explicitly anyway, as it makes the code clearer as well as silencing the warning.

提交回复
热议问题