Skip to content

Commit c63b8fc

Browse files
ankaneScooletz
andcommitted
Reduced allocations for SparseVector - resolves #54
Co-authored-by: scooletz <[email protected]>
1 parent 6129125 commit c63b8fc

File tree

1 file changed

+30
-18
lines changed

1 file changed

+30
-18
lines changed

src/Pgvector/SparseVector.cs

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -29,43 +29,55 @@ public SparseVector(int dimensions, ReadOnlyMemory<int> indices, ReadOnlyMemory<
2929
public SparseVector(ReadOnlyMemory<float> v)
3030
{
3131
var dense = v.Span;
32-
var indices = new List<int>();
33-
var values = new List<float>();
32+
var count = 0;
33+
var capacity = 4;
34+
var indices = new int[capacity];
35+
var values = new float[capacity];
3436

3537
for (var i = 0; i < dense.Length; i++)
3638
{
3739
if (dense[i] != 0)
3840
{
39-
indices.Add(i);
40-
values.Add(dense[i]);
41+
if (count == capacity)
42+
{
43+
capacity = capacity >= dense.Length / 2 ? dense.Length : capacity * 2;
44+
Array.Resize(ref indices, capacity);
45+
Array.Resize(ref values, capacity);
46+
}
47+
48+
indices[count] = i;
49+
values[count] = dense[i];
50+
count++;
4151
}
4252
}
4353

4454
Dimensions = v.Length;
45-
Indices = indices.ToArray();
46-
Values = values.ToArray();
55+
Indices = new ReadOnlyMemory<int>(indices, 0, count);
56+
Values = new ReadOnlyMemory<float>(values, 0, count);
4757
}
4858

4959
public SparseVector(IDictionary<int, float> dictionary, int dimensions)
5060
{
51-
List<KeyValuePair<int, float>> elements = dictionary.ToList();
52-
elements.Sort((a, b) => a.Key.CompareTo(b.Key));
61+
var count = 0;
62+
var capacity = dictionary.Count;
63+
var indices = new int[capacity];
64+
var values = new float[capacity];
5365

54-
var indices = new List<int>();
55-
var values = new List<float>();
56-
57-
foreach (KeyValuePair<int, float> e in elements)
66+
foreach (var e in dictionary)
5867
{
5968
if (e.Value != 0)
6069
{
61-
indices.Add(e.Key);
62-
values.Add(e.Value);
70+
indices[count] = e.Key;
71+
values[count] = e.Value;
72+
count++;
6373
}
6474
}
6575

76+
Array.Sort(indices, values, 0, count);
77+
6678
Dimensions = dimensions;
67-
Indices = indices.ToArray();
68-
Values = values.ToArray();
79+
Indices = new ReadOnlyMemory<int>(indices, 0, count);
80+
Values = new ReadOnlyMemory<float>(values, 0, count);
6981
}
7082

7183
public SparseVector(string s)
@@ -84,8 +96,8 @@ public SparseVector(string s)
8496
}
8597

8698
Dimensions = Int32.Parse(parts[1], CultureInfo.InvariantCulture);
87-
Indices = indices.ToArray();
88-
Values = values.ToArray();
99+
Indices = indices;
100+
Values = values;
89101
}
90102

91103
public override string ToString()

0 commit comments

Comments
 (0)