[swift-evolution] [Review] Require self for accessing instance members

Charles Srstka cocoadev at charlessoft.com
Sat Dec 19 12:33:11 CST 2015


> On Dec 19, 2015, at 12:23 PM, Charles Srstka via swift-evolution <swift-evolution at swift.org> wrote:
> 
>> On Dec 19, 2015, at 3:02 AM, Tino Heth <2th at gmx.de <mailto: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.

Another thing worth keeping in mind is that Apple has stated interest in fixing the fragile base-class problem in Swift (as, indeed, they will need to if it is to be usable as a framework language). However they solve this, it will have to create some kind of layer of indirection indirection when accessing instance members of classes (and possibly even structs, if they decide that framework authors should have the flexibility to add things to those as well). A small penalty, but still one to be aware of.

Charles

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20151219/5ce9f698/attachment.html>


More information about the swift-evolution mailing list