开发者

Best practice for reused variable?

开发者 https://www.devze.com 2023-03-14 02:58 出处:网络
I am trying to understand a point, i know that in this case it might be negligible. When i call, lets say:

I am trying to understand a point, i know that in this case it might be negligible.

When i call, lets say:

float w = object.frame.size.width;

Does the program "calculates" that each time I call it, or does it stores this data on object creation.

I mean what is the difference (in memory usage) between :

float w = object.frame.size.width;
float g = object.frame.size.width;
float s = object.frame.size.width;

And :

float newVar = object.frame.size.width;
float w = n开发者_运维百科ewVar;
float g = newVar;
float s = newVar;

Thanks

Shani


object.frame.size.width might (and in this case, does) only read and return some c struct property, but bear in mind these can be real objective-c method calls, such as object.color.

Let's use another example where it's not so obvious. You can call object.description on every object to get a string description of that object. That's clearly the same as the method call [object description]. Do you know what all has to be done to get the description? It's up to the implementor of that method, but there's nothing stopping them from doing something expensive, desructive, or otherwise stupid.

object.doSomethingVeryComplicated will work. It's not how you're supposed to use dot notation, and you should never do something very complicated in your getters and setters, and they should never do anything to your object (except lazily initializing it), but there are no hard barriers in place to prevent you from doing this kind of stuff. It's "only" convention. You could even, theoretically, do object.tellMeYourColorAndThenGiveYourselfANewRandomColor. Now there would obviously be three different answers for your first, and only one answer for your second example.

It's up to the implementor of getter and setter methods (which are the only methods supposed to be called via dot notation) to ensure this kind of frivolity does not happen, but there's nothing stopping the caller of a method to call destrucitve methods that weren't intended to be used that way via dot notation. Dot notation is a tool for you, the writer, to indicate simple get/set actions to readers of your code (including yourself).

So, I don't think the compiler can optimize/abstract example one into example two. But I'm not sure, maybe it really does analyze code so deeple that it knows when this is possible, and when it isn't. Or maybe it's possible when it really is only an access to a c struct, as in your example, but not when it's a real method call. In any case, do you always know which one it is, and what the implications are? I'd go for clarity in my code instead of brevity.

0

精彩评论

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

关注公众号