Skip to content

Proposal: Vector.Sum(Vector<T>) API for horizontal add #35626

@Sergio0694

Description

@Sergio0694

Overview

This issue is about adding a new API to System.Numerics.Vector:

namespace System.Numerics
{
    public static partial class Vector
    {
        public static T Sum<T>(Vector<T> vector) where T : struct;
    }
}

This API would perform the (unchecked) sum of all T items in the given Vector<T> register.

Motivation

Today, the best way to do a horizontal sum of items in a Vector<T> register is to use Vector.Dot with a unit vestor (Vector<T>.One), this has a number of disadvantages:

  • It is not intuitive for users (imagine looking for some "sum" methods and not seeing it). Also, many devs might not be familiar with how the dot product works exactly, or wouldn't think of this solution immediately when just going through the IntelliSense results.
  • Using Vector.Dot requires occupying a second SIMD register that's not actually needed if we only care about doing a horizontal sum. Not having to use that second register at all will give the JIT more room to do other optimizations (and also avoid having to load that register at all).
  • Using Vector.Dot also adds the unnecessary multiplication instruction, which we don't need.

This new Vector.Sum API would basically compile to the same overall code produced by Vector.Dot, mostly just skipping the initial multiplication and only taking one register as input.

cc. @tannergooding

Metadata

Metadata

Assignees

Labels

api-approvedAPI was approved in API review, it can be implementedarea-System.Numericshelp wanted[up-for-grabs] Good issue for external contributors

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions