Why is Vector<T>.Count static?

1.7k views Asked by At

I'm trying to use System.Numerics.Vector<T> (documentation).

I wrote a simple unit test:

var v = new System.Numerics.Vector<double>(new double[] { 12, 13, 14 });
Assert.AreEqual(3, v.Count);

But it gave me a build error:

Member 'Vector.Count' cannot be accessed with an instance reference; qualify it with a type name instead

To my surprise, Vector<T>.Count is static.

So I tried:

var v = new System.Numerics.Vector<double>(new double[] { 12, 13, 14 });
Assert.AreEqual(3, Vector<double>.Count);

Now the code builds but the unit test fails:

Assert.AreEqual failed. Expected:<3>. Actual:<2>.

What's going on?


Investigating I found:

Assert.AreEqual(2, Vector<double>.Count);
Assert.AreEqual(4, Vector<float>.Count);
Assert.AreEqual(4, Vector<int>.Count);
Assert.AreEqual(2, Vector<long>.Count);
2

There are 2 answers

3
BartoszKP On BEST ANSWER

The documentation suggests that this is by design:

The count of a Vector instance is fixed, but its upper limit is CPU-register dependent.

Its purpose is to allow vectorizing operations using hardware capabilities, and thus its capacity is tied to your CPU's architecture.

0
Andrey On

Vector may be somewhat confusing type. It is fixed predefined-length collection. It is fixed because its length is always == Vector<T>.Count. So if you do:

var v = new Vector<double>(new double[] { 12, 13, 14 });
Console.WriteLine(v);

result is... :

<12, 13>

It is just drops all values over Vector<double>.Count which happens to be 2. The trick is that Vector<T>.Count may vary based on CPU architecture.

It is actually pretty low level primitive, as description says:

Represents a single vector of a specified numeric type that is suitable for low-level optimization of parallel algorithms.