Single Element Sets

How efficient is Swift at handling single element sets?

I have a wrapper type around Set where 80% of all the sets will have a single element. Is it worth special casing this in my wrapper (say with an enum or protocol), or will Set special case this itself?

With regards to memory efficiency, I think Set will be pretty good as it's strategy is to start off just reserving space for one element (or it may be two, I'm not sure) and then if further elements are added then every time it needs more space it doubles the size of the buffer.

With regards to speed efficiency, I'm afraid I don't know the library well enough to know.
I see your idea of wrapping in an enum.
To see whether that would help with speed, you could try benchmarking it perhaps?

You could try looking in the Swift implementation of Set at:


The buffers get a bit convoluted :-]

1 Like

You might also try using the Set in all cases and then profiling with Instruments to see if the single item case is a performance hot spot.

1 Like