tags:

views:

173

answers:

3

Hi,

When designing an API, I may want to persist details (Eg of a process running) into my own custom struct. However, if I am going to do this for more than 1 process, meaning I need several structs, should I have an array of structs or one struct with an array for each of its properties (eg startTime, processName and other process properties I am interested in).

Which way is better for performance and better for an api/class library?

Thanks

+1  A: 

You might consider using a class rather than a struct and I would use a list of classes.

Stan R.
+2  A: 

IMHO you should do an array of structs despite the performance hit you take for instansiating all of the structs. The organizational sense of one state being stored in one struct far outweighs the loss of performance, and using one struct with a bunch of arrays and simply assigning each process an index in a number of arrays is very messy and can be a huge pain to debug.

Steve H.
Makes sense with the organisation point. One struct/one process. Any example of how the other approach would be hard(er) to debug?
dotnetdev
I'm sure I don't need to show you the code because it is trivial. It would be harder to debug in two ways I think. If you leave the code alone for a while and come back to it, it may look confusing - especially if you need to peek forwards or backwards ever and see a lot of StartTime[x-1] or ProcessID[x+2]. Those ones and twos can seem arbitrary after a long time, so just having each process in a class or struct just makes life easier. Also that is very dangerous and can get ArrayOutOfBounds exceptions.
Steve H.
There is also the performance hit of making an array/list/dictionary etc. larger. If your array(s) initially are size 5, and you add a 6th process, you only have one array to resize instead of one for each property you'd like to persist. I recommended the list for the ease of using a foreach(customStruct s in listOfProcesses){} so you can avoid int len = listOfTimes.Length(); for(int i = 0; i < len; i++){ startTimeList[i] <something something> ; processNameList[i] <something something> ; ...}
Steve H.
A: 

Eric Lippert has a few arguments against using arrays in an API. One of the more compelling to me is why you'd want to keep the collection size fixed, but allow consumers to modify the contents. You can see more here.

Ultimately, you may want to store them internally using arrays, but I would avoid exposing this through the API. If people need to enumerate, use IEnumerable<T> instead.

micahtan