NSKeyValueCoding: Safe-Caching for -[NSObject valueForKey:]
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 to libobjc2 here: https://github.com/gnustep/libobjc2/commit/f7a38aa9979175f61e476f6d3a7e2d15aa50ba33.
Any idea why the new type test fails for gcc and would it pass without your changes to GSRuntime?
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.
@rfm it would be great if you could take another look at this PR :) I've moved some known CoreGraphics struct types into their proper header to improve compatibility with Apple Frameworks.