简体   繁体   中英

What is the most efficient way to store the location of 4 properties (NSPoints)?

So I am passing a view into a method, and I want to find the properties of some values from a CGRect that is contained within the view.

- (void)blahblah:(someView*)view
  int originX = view.myCGRect.origin.x;
  int originY = view.myCGRect.origin.y;
  int width = view.myCGRect.size.width;
  int height = view.myCGRect.size.height;

would this be a better way of writing it?

- (void)blahblah:(someView*)view
  CGRect sameCGRect = view.myCGRect;
  int originX = sameCGRect.origin.x;
  int originY = sameCGRect.origin.y;
  int width = sameCGRect.size.width;
  int height = sameCGRect.size.height;

Or is there an even more efficient way of doing this?

Also, I'm new to objective-C so could somebody explain if there even is a difference between these two implementations; and if so, what is it?

In reference to the older, previously accepted answer:

In this case the compiler would not be able to perform the subexpression elimination automatically. The reason is that view.myCGRect is actually a dynamically dispatched message.

Since the compiler does not know in advance which method will be called and what side effects it might have it cannot just drop the redundant calls because there might be a semantic difference.

The second code snippet will be more performant.

See Comments: What you're talking about doing is manual "common subexpression elimination", where a common value (view.myCGRect in this case) is "hoisted" ahead of several references to it. This is especially effective for loops, when the common code is placed outside the loop. But for most (but not all) cases the compiler (or JITC for Java) will be able to recognize these CSEs and "hoist" them automatically. However, I still find that the code is often easier to follow (and maintain) if you do the manual operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM