3 ms·
It's not the concept of arrays that are the problem - it's the implementation of them. As the author points out, it's easy to use arrays to accidentally create
by Aaronontheweb 16y ago
It's not the concept of arrays that are the problem - it's the implementation of them. As the author points out, it's easy to use arrays to accidentally create a memory hog application that doesn't perform well in multi-core environments.
It's better to abstract arrays through the use of more sophisticated classes like IList in .NET, which can mitigate the issues with traditional primitive arrays and provide developers with something that works better in modern multi-core scenarios.
- flatline 16y agoTechnically System.Array also implements IList, which is an interface behind which sit several implementations. The generic List type is probably worse than a plain old array, as it is really a mutable, resizable array implementation. Even the author states "one might reasonably point out that List<T> is a mass of mutable state too". Future-proofing yourself through the IList abstraction is a good practice, but I'm not sure off-hand what you would use to replace it that would be better, for now. I got the impression that the author was arguing for strictly immutable data structures, which you can achieve through diligent use of the readonly attribute and private setters, but which is not otherwise a native concept in C# or VB. I hope more of the F# immutable structures make it into the core framework in the future.
- Aaronontheweb 16y agoAs a general practice it's bad to return List<T> for that reason - it's bloated with additional members and state to match to support just-about-anything out of the box. Return IList instead of List on any public interface you define is the rule I try to obey. Basically it's all about how you implement arrays in your called classes - do they expose some internal state by returning a deep clone of the array each time it's called (which is what the examples Eric used were doing) or does it expose its contents via a read-only List?
- euroclydon 16y agoYeah, but which hard class do you return as an IList? Does the bloat go away if you return a List from an IList typed method?
- chromic 16y agoThe bigger picture would be: 1) Don't give a reference to your mutable private/shared variables because it's dangerous. 2) Because we still need to let people read this data, give them copies (of a potentially large structure) instead and lose performance. It just happens to be that arrays are a common case.