Search code examples
core-dataentityrelationship

Core Data: 1:1 Relationship to other entity or keep everything in one entity?


I have an Entity in Core Data that contains multiple "small" attributes like String and Int. But I also have one binary attribute that contains ~500kb data. This attribute is specific and unique for each dataset.

I'm now wondering if I should create a new entity only for this attribute (using relationship)

Are there any performance problems when I keep this attribute in one entity? I'm asking because I checked a few online example projects using Core Data that created a dedicated entity for large data.


Solution

  • That's a common setup, as you've seen. Whether it's good depends very much on the performance implications. The point of this technique is to avoid loading the binary data except when it's necessary. By doing this:

    • If you use the entity but often you don't need the binary data (i.e. you just use the other properties), you'll reduce memory use by not loading the data blob. How much depends on how frequently you need that data-- the less often you need it, the better for memory use.
    • If you always use the binary data, you break even, there's no improvement in memory use.
    • Using this technique might be very slightly slower than putting the binary data in the main entity, since you need to run some extra code to load it. It's a small enough difference that you'd probably need to do careful performance profiling to notice.

    If the binary data is an image, another common technique is to combine the two by including a scaled-down thumbnail in the entry, and put the full size image somewhere else. Then you can display smaller images (in a list or table view maybe) but still get most of the memory improvement of using a separate entity.