Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory efficient way to store many small objects

I have a simple Person class with 4 strings and integer.

public class Person
{
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public string PostalCode { get; set; }
}

We need to store a large number of these in memory. The collection needs to be searchable by any field. Items will be added and deleted as part the life cycle.

The Flyweight pattern doesn't seem work because there isn't a ton of duplicate values at the object, only at the field level. What pattern or strategy would work best to limit memory overhead and perform well?

like image 766
user2547359 Avatar asked Nov 13 '22 02:11

user2547359


1 Answers

We need to store a large number of these in memory.

Then an array Person[] would be the leanest way but a List<Person> would be close and much easier to work with. Just make sure to minimize re-allocation by using the Capacity parameter.

The collection needs to be searchable by any field

Easy, .Where (p => p.FirstName == value).
Speeding it up with Dictionaries will cost memory.

like image 141
Henk Holterman Avatar answered Nov 15 '22 00:11

Henk Holterman