Question

I'm subclassing UIView to make a custom view by overriding drawRect:. I need to find a point that is equal to 10 percent of the View's width. Of course, that distance is trivial to calculate (self.bounds.size.width/10.0f). I would like to cache this value, that is, I want to store this value in an instance variable to avoid having to calculate it on every single drawRect:.

Inside what method would I store this value? I was thinking about just saving the variable's value while in initWithFrame:, but then the cached value would be out of sync with the view's width after any sort of resize.

Any thoughts on what the best place to cache the view's width is... and if it is even ok to do so?

Was it helpful?

Solution

You can store the value in an ivar and (re)compute it in layoutSubviews.

However, this is an obvious case of premature optimization. You should focus on writing good code, and optimize when the need becomes apparent. In fact, this "optimization" could even have a negative impact on your app's performance: is it more expensive to divide two numbers or to look up the value of an ivar?

OTHER TIPS

that distance is trivial to calculate (self.bounds.size.width/10.0f)...

I would like to cache this value, that is, I want to store this value in an instance variable to avoid having to calculate it on every single drawRect:.

Everything here is trivial. There is no reason to cache it.

You have:

  • one objc message (which you would use to access a cached value)
  • then you access a field of a struct within a struct (practically free)
  • then you perform a floating point divide (still tiny relative to the operation)

Any thoughts on what the best place to cache the view's width is... and if it is even ok to do so?

The best place is right here:

- (void)drawRect:(CGRect)rect {
  // ...
  const CGFloat tenthWidth = self.bounds.size.width * 0.10f;
  // ...
}

also note the use of multiplication by the reciprocal ;)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top