Pergunta

I have two private arrays in a class that runs a certain operation using a method. After this method is called, those two arrays are filled with the results. It's not a good practice to make those arrays properties, so I was planning to have a separate property that returns a clone of the private array.

1) What is the overhead of returning a clone of the array? Is it unnoticeable in every case?

2) I could use an indexer if there was just one array. Is there a specific mechanism to use indexers for more than one array in a class?

Foi útil?

Solução

I think you mean "overhead" or "cost" and not "overload". Anyway, computationally it's O(1) so it depends on the size of tha rray, but generally speaking Array copying is a cheap operation if it's under a thousand elements or so.

If you don't intend on the arrays to be modified then you could expose your private arrays by wrapping them in a ReadOnlyCollection<T> like so:

private TWhatever[] _array;
public ReadOnlyCollection<TWhatever> Elements { get; private set; }

public ClassConstructor() {
    _array = new TWhatever[1000];
    this.Elements = new ReadOnlyCollection<TWhatever>( _array );
}

Outras dicas

Cloning an array is a memory allocation; the impact will depend directly on the size of the array.

An indexer is just a method; another approach might be to just add a method such as GetName(int index) and GetValue(int index) (if your arrays are names/values, for example). There aren't inbuilt named indexers in C#, alas.

If performance is important, and you will need to access multiple values, then another approach is to have a method that copies the values to an array the caller supplies, for example GetNames(string[] names, int offset) { this.names.CopyTo(names, offset); }. This can be useful by allowing the caller to allocate a single buffer, and then use it to obtain values from multiple objects - or if you add a few parameters (for the count etc), to obtain the values in batches rather than individually. Whether this is necessary / useful depends a lot on the exact scenario, though.

Maybe is it possible to do something like this

KeyValuePair this[int i] { get { /* code */ } private set{ /* code */ } }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top