Array of structs or one struct with array for each of its properties
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?
T开发者_JAVA技巧hanks
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.
You might consider using a class
rather than a struct
and I would use a list of classes.
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.
From a data-storage standpoint, if one will frequently be accessing all the parts of an items more often than one would be accessing some particular part from a group of consecutive items, caching behavior will be better with an array of structs.
A more interesting question is how to expose the data. If you expose the struct as an indexer, anyone wanting to change a field of the struct will have to read out the struct, change the field in their temporary copy, and write it back. You could expose methods to read/write individual properties, but "foo.setBar(100, 23)" seems rather less natural than "foo(100).Bar=23". Too allow the latter syntax, I'd suggest perhaps having the indexer return a struct with two private fields, "root" and "index", and properties for each field of the struct so that e.g. the setter for the Bar property of the indexer would perform root.setBar(index, value). The indexer should also have an "asWhateverStructType" property to get/set the struct as a whole.
精彩评论