开发者

Shall I cache it?

开发者 https://www.devze.com 2023-02-05 13:46 出处:网络
When having a class: class X { int data_; void f() { //shall I cache var data_? by doing int cached = data_ //and instaed of this:

When having a class:

class X
  {
  int data_;
  void f()
    {
    //shall I cache var data_? by doing
    int cached = data_
    //and instaed of this:
    if (data_ >= 0 && data_ < 1000 || data_ < 0 && data_ > -1000)//first version
      {
      //do something
      }
    else
      {
      //do somegthing else
      }
    // have this:
    if (cashed >= 0 && cashed < 1000 || cashed < 0 && cashed > -1000)//sec开发者_C百科ond version
    // in my opinion this is bad code
      {
      //do something
      }
    else
      {
      //do somegthing else
      }
    }
  };

Please see comments in code.

I'm asking this question because my accomplice from university states that this kind of code (line 1) is just a bad code. I think that he's talking rubbish but I'm very interested in your opinion on this subject.

Thank you.


*Cached

And unless your data_ variable may change halfway through execution, there is no difference whatsoever between those two code segments.


Don't optimize unless it is already too slow: Write the clearest, simplest possible code, measure it, and if it is too slow, use tools to discover (not guess) which part is the slowest. If possible, use a better algorithm before deploying caching & other minor optimizations. In any case, once you've optimized that part, measure it again, and if it it's still too slow, repeat.

That being said, @Zhais is correct. There's no functional difference in the two code snippets.


This kind of optimization is called premature optimization. You should not do optimization like that until it is proven to be the bottleneck.

In the first case the variable is actually used as this->data_ but you can't be sure because compiler may cache it himself.

0

精彩评论

暂无评论...
验证码 换一张
取 消