The Swift Reflection API and what you can do with it

Performance

released Fri, 01 Mar 2019
Swift Version 5.0

Performance

So we just wrote some code that converts struct types via reflection at runtime to Core Data types. How fast is this? Can this be used well in production? I did some testing:

Create 2000 NSManagedObjects

Native: 0.062 seconds
Reflection: 0.207 seconds

Native, here, means creating an NSManagedObject and setting the property values via setValueForKey. If you create a NSManagedObject subclass within Core Data and set the values directly on the properties (without the dynamic setValueForKey overhead) this is probably even faster.

So, as you can see, using reflection slows the whole process of creating NSManagedObjects down by about 3.5x. This is fine when you're using this for a limited amount of items, or when you don't have to care about speed. However, when you need to reflect over a huge amount of structs, this will probably kill your app's performance.