MethodsTypes |
In order to provide maximum flexibility and optimize memory layouts we use to have multiple implementations of frequently needed operations. We use the following convention: when it's possible we implement three version of each operation: In place, Out of place and Result Returning. Let's describe the difference considering an example of addition of two instance of class Vector.
Note |
---|
For arithmetic operation you can alternatively use overloaded operations like '+' or '+=' instead of methods calling. |
Result Returning: The most obvious one. It performs operation out of place, i.e. it doesn't change operand's memory, and, in fact, it allocates memory, and put result in it. After that it returns result. So when you want to add two vectors and get new one as result, you simply can write:
1public static Vector SimpleSum1(Vector x, Vector y) 2{ 3 // Result will allocated and returned. 4 return x.Add(y); 5}
1public static Vector SimpleSum2(Vector x, Vector y) 2{ 3 return x + y; 4}
Out of place: result will be placed in additional result parameter, as previous those methods do not change operand's memory.
Caution |
---|
Caller is responsible for result's memory allocation. |
1public static void ShowSum1(Vector[] first, Vector[] second) 2{ 3 // Result vector will be allocated for each operation. 4 for (int i = 0; i < first.Length; ++i) 5 Console.WriteLine((first[i] + second[i]).ToString("0.000")); 6 // Or calling Add method: Console.WriteLine(first[i].Add(second[i])); 7}
1public static void ShowSum2(Vector[] first, Vector[] second) 2{ 3 // Preallocate memory. 4 Vector result = new Vector(first[0].Count); 5 for (int i = 0; i < first.Length; ++i) 6 { 7 // Store result in preallocated memory. 8 first[i].Add(second[i], result); 9 // Show result. 10 Console.WriteLine(result.ToString("0.000")); 11 } 12}
In place: result will be placed in first operand. It can be very useful if you no longer need one of the operation's argument (and of course if this argument has enough memory to store result). For example, if one argument is only temporary collection. Assume you want to summarize number of vectors. So you can:
1public static Vector Summarize1(Vector[] vectorset) 2{ 3 // Assume that we have at least one vector. 4 Vector result = vectorset[0]; 5 6 // Result will be reallocated on each operation. 7 for (int i = 1; i < vectorset.Length; i++) 8 result = result.Add(vectorset[i]); 9 10 // Alternatively you can write: 11 // result = result + vector[i]; 12 // Or result += vector[i]; 13 14 return result; 15}
1public static Vector Summarize2(Vector[] vectorset) 2{ 3 // Preallocate result vector. 4 Vector result = vectorset[0].Clone(); 5 // Result will be placed in result vector without allocations. 6 for (int i = 1; i < vectorset.Length; i++) 7 result.AddInPlace(vectorset[i]); 8 9 return result; 10}