From: zthhhhh (@zthhhhh) <noreply+zthhhhh@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] issue #991: Optimize zero-vector detection in vector_norm with early exit
Date: Wed, 24 Jun 2026 16:35:13 +0000
Message-ID: <gh-pgvector-pgvector-991@github.com> (raw)
The `vector_norm`function computes the full Euclidean norm:
https://github.com/pgvector/pgvector/blob/master/src/vector.c#L763
In practice, `vector_norm ` is used as the NORM_PROC in HNSW and IVF operator classes (e.g. vector_cosine_ops) to detect all-zero vectors so they can be skipped during index building and insertion. For example, HnswCheckNorm and IvfflatCheckNorm both check vector_norm(...) > 0 , they only care whether the vector is zero, not the actual norm value.
Because of this, vector_norm always iterates through every element (computing squares and sqrt), even if the first element is already non-zero. This is wasteful when the only goal is zero detection.
A simple early-exit optimization can reduce the loop cost for non-zero vectors (the vast majority in practice):
```
for (int i = 0; i < a->dim; i++)
{
if (ax[i] != 0)
{
norm = 1.0;
break;
}
}
```
I'd like to propose adding a lightweight zero-check function (or optimizing the NORM_PROC usage) so that the index build/insert hot path doesn't pay the cost of a full Euclidean norm when only zero-detection is needed.