Skip to content

[Performance] Proposal - aligned new and stackalloc with alignas(x) for arrays of primitive types and less primitive as well #1799

Closed
@4creators

Description

@4creators

Problem statement

One of the pain points while working with hardware intrinsics is to keep data aligned to boundaries accepted by used instructions. Usual expectations are that data will be aligned on 16 byte or 32 byte boundaries. Possibly there are many solutions to doing this using attributes for non primitive data types, however, one place where it does not work is allocation of arrays composed of primitive types (byte, int, float, double).

For instance following expression may not allocate array on 16 or 32 byte boundaries:

double* dPtr = stackalloc double[10];

The size of array is equal to 80 bytes and is divisible by 16 but not by 32. Possible allocations on stack may happen with smaller than 16 alignment. Similar problem will arise in case of Array allocations on heap.

double[] dArr = new double[10];

Essentially developer has no control over allocation alignment of the buffer which is pointed to from Array class. Similar problems arise when developers would like to store in assembly initialization data for arrays. Essentially there is no control how blob data in assembly will mapped into memory.

Essentially the only ways to control primitive arrays alignment (I could be wrong) are either to use sequential/fixed layout in structures with fixed arrays and StructLayout.Pack property or by using pointer aligning functions. IMO it places to much burden on developers needed to write high performing code with Hardware Intrinsic and even with simple loop blocking optimization techniques.

Proposal

One of the simplest solutions from perspective of developers using such feature would be introduction of new keyword alignas (yes, exactly the same as in C++ standard) which could proceed or follow allocation declarations with new or stackalloc keywords.

MyStruct[] msArr = new alignas(16) MyStruct[256];
MyStruct  ms = new alignas(32) MyStruct();

double* stackArray = stackalloc alignas(32) double[64];

Alternatives

One of the ugly approaches used for stackalloc with enforced tricked alignment is to allocate amount of memory very slightly below the memory page size what usually leads to allocation on memory page boundary or usage of functions adjusting the native pointer to array.

There are no effective methods to control Array buffer alignment on heap.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions