I have a file with 2 columns and multiple rows. 1st column is ID, 2nd column is Name. I would like to display a Dropdown where I will show only all the names from this file.
I will only iterate through the collection. So what is the better approach? Is creating the objects more readable for other developers? Or maybe creating new objects is too slow and it’s not worth.
while (!reader.EndOfStream)
{
var row = reader.ReadLine();
var values = row.Split(' ');
list.Add(new Object { Id = int.Parse(values[0]), Name = values[1] });
}
or
while (!reader.EndOfStream)
{
var row = reader.ReadLine();
var values = row.Split(' ');
dict.Add(int.Parse(values[0]), values[1]);
}
>Solution :
Do I lose the speed in the case if I will create new objects?
You create new objects, so to speak, also while adding to the Dictionary<T>
, you create new Key-Value pair of the desired type.
As you already mentioned in your question, the decision is made on primary
- expected access pattern
- performance considerations, which are the function also of access pattern per se.
If you need read-only array to iterate over, use List<T>
(even better if the size of the data is known upfront use Type[]
data, and just read it where you need it).
If you need key-wise access to your data, use Dictionary<T>
.