-
Notifications
You must be signed in to change notification settings - Fork 282
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
NSKeyValueCoding: Safe-Caching for -[NSObject valueForKey:] #445
Conversation
Any idea why the new type test fails for gcc and would it pass without your changes to GSRuntime? |
Not sure. I'd need to setup a GCC environment to debug this. Failed test: (2024-09-07 10:06:20.004 +0000) types.m:312 ... Ivar returns NSPoint
Failed test: (2024-09-07 10:06:20.004 +0000) types.m:314 ... Ivar returns NSRange
Failed test: (2024-09-07 10:06:20.004 +0000) types.m:316 ... Ivar returns NSRect
Failed test: (2024-09-07 10:06:20.004 +0000) types.m:318 ... Ivar returns NSSize
Failed test: (2024-09-07 10:06:20.004 +0000) types.m:320 ... Ivar returns MyStruct |
Test failures are unrelated. |
@rfm, @fredkiefer, it would be great if you could take another look at it. |
… NSSize have the same layout
…ing with CoreGraphics
@rfm it would be great if you could take another look at this PR :) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
All seems to be reasonable to me.
It turns out that valueForKey: is a very expensive operation, and a major bottleneck for Key-Value Observing and other operations such as sorting an array by key.
The accessor search patterns for Key-Value observing are discussed in the Apple Key-Value Coding Programming Guide. The return value may be encapsulated into an NSNumber or NSValue object, depending on the Objective-C type encoding of the return value. This means that once valueForKey: found an existing accessor, the Objective-C type encoding of the accessor is retrieved. We then go through a huge switch case to determine the right way to invoke the IMP and potentially encapsulate the return type. The resulting object is then returned.
The algorithm for setValue:ForKey: is similar.
We can speed this up by caching the IMP of the accessor in a hash table. However, without proper versioning, this quickly becomes very dangerous. The user might exchange implementations, or add new ones expecting the
search pattern invariant to still hold. If we clamp onto an IMP, this invariant no longer holds.
Apple actually just caches the IMP without versioning, as there is no support for safe-caching in
objc4
.We will make use of libobjc2's safe caching to avoid this.
Note that the caching is opaque. You will only need to redirect all
valueForKey: calls to the function below.
Note that the Implementation requires
method_getTypedSelector_np
which was added tolibobjc2
here: gnustep/libobjc2@f7a38aa.