Skip to content

Commit 1bb030b

Browse files
committed
Reduced allocations for SparseVector - #54
1 parent 80e4c0b commit 1bb030b

File tree

1 file changed

+7
-10
lines changed

1 file changed

+7
-10
lines changed

src/Pgvector/SparseVector.cs

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,30 +30,27 @@ public SparseVector(ReadOnlyMemory<float> v)
3030
{
3131
var dense = v.Span;
3232
var count = 0;
33-
var capacity = 4;
33+
var capacity = 0;
34+
35+
for (var i = 0; i < dense.Length; i++)
36+
capacity += Convert.ToInt32(dense[i] != 0);
37+
3438
var indices = new int[capacity];
3539
var values = new float[capacity];
3640

3741
for (var i = 0; i < dense.Length; i++)
3842
{
3943
if (dense[i] != 0)
4044
{
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-
4845
indices[count] = i;
4946
values[count] = dense[i];
5047
count++;
5148
}
5249
}
5350

5451
Dimensions = v.Length;
55-
Indices = new ReadOnlyMemory<int>(indices, 0, count);
56-
Values = new ReadOnlyMemory<float>(values, 0, count);
52+
Indices = indices;
53+
Values = values;
5754
}
5855

5956
public SparseVector(IDictionary<int, float> dictionary, int dimensions)

0 commit comments

Comments
 (0)