1

Take the following C# method:

static double[] AddArrays(double[] left, double[] right)
{
    if (left.Length != right.Length) {
        throw new ArgumentException("Arrays to add are not the same length");
    }

    double[] result = new double[left.Length];
    for (int i = 0; i < left.Length; i++) {
        result[i] = left[i] + right[i];
    }

    return result;
}

As I understand it, the CLR will initialize result to all zeros, even though AddArrays is just about to completely initialize it anyway. Is there any way to avoid this extra work? Even if it means using unsafe C#, C++/CLI, or raw IL code?

EDIT: Can't be done, for the reasons described here.

Community
  • 1
  • 1
Wesley Hill
  • 1,789
  • 1
  • 16
  • 27
  • 3
    See: http://stackoverflow.com/questions/648814/direct-array-initialization-with-a-constant-value – Shog9 Jan 24 '10 at 02:55

1 Answers1

3

You should do this instead:

static IEnumerable<double> Add(IEnumerable<double> left, IEnumerable<double> right)
{ 
    using (IEnumerator<double> l = left.GetEnumerator())
    using (IEnumerator<double> r = right.GetEnumerator())
    {
        while (l.MoveNext() && r.MoveNext())
        {
            yield return l.Current + r.Current;
        }

        if (l.MoveNext() || r.MoveNext())
            throw new ArgumentException("Sequences to add are not the same length");
    }
}

You can pass your double arrays to this function. If you really need an array as the result (hint: you probably don't) you can just call .ToArray() on the function's return value.

.Net 4 will have a function already built in for this:

 double[] array1 = {1.0, 2.0, 3.0};
 double[] array2 = {4.0, 5.0, 6.0};
 IEnumerable<double> result = array1.Zip(array2, (a,b) => a + b);

 foreach(double d in result)
 {
     Console.WriteLine(d);
 }
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • Unfortunately, I do need the result in array form eventually, though this gives me an idea for seeing how long lazy-evaluation could work in my situation (e.g., to combine two operators into one realized operation). – Wesley Hill Jan 26 '10 at 12:42