I was reading up on data structures from Code Complete. This is when I stumbled through this piece about arrays:
Think of arrays as sequential structures Some of the brightest people in computer science have suggested that arrays never be
accessed randomly, but only sequentially (Mills and Linger 1986).
Their argument is that random accesses in arrays are similar to random
gotos in a program: Such accesses tend to be undisciplined, error
prone, and hard to prove correct. Instead of arrays, they suggest
using sets, stacks, and queues, whose elements are accessed
sequentially.
Does this hold true for System.Array
class in C#?
14
It certainly does. Arrays in C# are very similar to arrays in other programming languages.
Some differences between dynamically allocated arrays in C and arrays in C#:
- In C#, array always knows its length.
- You can’t use pointer arithmetic in C# (unless you use
unsafe
). This means that part of the array can’t be represented as (pointer, length), it has be represented as something like (reference, start_index, length).
But none of these differences are relevant to the quote in question.
Also, C# makes it easy to treat array as a sequential structure: it implements IEnumerable<T>
and can be used in a foreach
(though neither of these allows you to modify the array). This means you can iterate though the array without using indexes. For example:
foreach (var item in array)
Console.WriteLines(array);
Or (using LINQ, which is based on IEnumerable<T>
):
var unavailableProducts = products.Where(p => p.InStock == 0);
7
The point is language-unspecific, so as far as it holds, it holds for C#. (The only exception would be if your language has arrays where random access is not O(1), but I can’t think of one off-hand.)
But of course there are situations in programing where you definitely don’t need to access all items in a collection, but only one particular item per request, and in such situations it can be useful to arrange the items in an array for fast access. I don’t think anyone would argue that random access per se is undisciplined and should be avoided in any situation – but in those where looping does the trick, it is indeed easier to program and to verify.
1