[swift-evolution] [Review] Require self for accessing instance members
Charles Srstka
cocoadev at charlessoft.com
Sat Dec 19 12:23:48 CST 2015
> On Dec 19, 2015, at 3:02 AM, Tino Heth <2th at gmx.de> wrote:
>
> imho the most valuable vote for mandatory self, just one comment on it
>
>> 1) Accessing a property, in a class, is more expensive than accessing a local variable. The above code would require three message sends and/or vtable accesses instead of one, if it were not assigning the property to a local variable. These unnecessary property accesses needlessly reduce the efficiency of the program.
> True for Objective-C, and might be true for Swift in many cases as well - but just because of legacy reasons:
> Correct me if I'm wrong, but I expect that simple getters have no performance penalty at all.
If a property isn’t marked final, it can be overridden by a subclass. That suggests to me that a vtable lookup is necessary at the very least. Keep in mind also that the property may be computed (and if it’s not, it might *become* a computed property at some point in the future), in which case the performance penalty could be *anything*. It could be an atomic property which takes a lock every single time it’s accessed. It could run some complex computation involving a host of other properties which themselves have unknown costs. It could even be doing something like loading something off the disk each time. Unless you have the source, you just don’t know. (And even if you *do* have the source, hunting down every single access of the property in the future won’t be fun if it becomes necessary to make the property computed in the future).
IMHO, best practice is to load the property once and then use the result of that, instead of spamming the getter over and over and over.
Charles
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151219/80867f82/attachment.html>
More information about the swift-evolution
mailing list