- Home /
Saving HashSet using BinaryFormat
I want to save a set of IDs in a file. I'm interesting on using HashSet because retrievals and deletions performs in constant time.
The problem: Unity does not have getObjectData method implemented on HashSet (method from ISerializable interface needed on BinaryFormat.Serialize and Deserialize methods).
What can I use in order to keep constant times? (lists and arrays are discarded because they have linear time complexity).
Answer by zach-r-d · Aug 02, 2015 at 03:23 AM
HashSet does allow constant time insert and delete, but it is not mathematically possible to serialize or deserialize a collection of an arbitrary number of objects in constant time, you must iterate over the elements (or the memory itself, but that would be less efficient).
The solution is to serialize an array of elements contained in the hashset, then convert that back into a HashSet when deserializing. If you look at the source of HashSet.cs in .NET, it's exactly what's happening under the hood in GetObjectData anyway.