Skip to content

Repository files navigation

ArrayBuffer

Just use Span if you can. I couldn't.

History

Here's some history; I wanted to get rid of codes like this:

list.Add("aaa");list.Add("bbb");list.Add("ccc");if(x){list.Add("ddd");list.Add("eee");}else{list.Add("fff");list.Add("ggg");list.Add("hhh");}

So I first tried doing something like this:

varlist=newList<string>{"aaa","bbb","ccc",};if(x){varadditions=new[]{"ddd","eee",};list.AddRange(additions);}else{varadditions=new[]{"fff","ggg","hhh",};list.AddRange(additions);}

Which made it look cleaner, but I wasn't so happy about making so many arrays just for the sake of making the code look cleaner.

ArrayBuffer makes the code look like this:

varbuffer=newArrayBuffer<string>(3);varlist=newList<string>();// Yay! Local functions!voidAddRange(ArrayBuffer<string>.Spanspan){using(span)list.AddRange(span);}AddRange(newArrayBuffer<string>.Span(buffer,3){"aaa","bbb","ccc",});if(x){AddRange(newArrayBuffer<string>.Span(buffer,2){"ddd","eee",});}else{AddRange(newArrayBuffer<string>.Span(buffer,3){"fff","ggg","hhh",});}

Which is still readable, and no more multiple allocations. Just keep the initial size the max size you need (new ArrayBuffer<string>(3)).

Usage

  1. Create a buffer first.
varbuffer=newArrayBuffer<string>(10);
  1. There are 2 ways you can create buffers.

    • Use Take.
    varspan=buffer.Take(10);
    • Create a new Span
    varspan=newArrayBuffer<string>.Span(buffer,10);
    • These are both essentially the same (Take just calls new Span) but creating a Span will give you the capability to use the Collection Initializer.
  2. Add items like normal arrays.

span[0]="hello";
  1. When you're done, call Return. After calling Return, you will no longer be able to access the items in the Span. Although accessing them will not crash your program, you should just put the Span in a using block.
span.Return();// betterusing(varspan=buffer.Take(10)){
...}

Notice

Do not use the Add method! The Add method is only there for using Collection Initializers. You will get an exception if you try to use Add.

Benchmark

Seems like using pure arrays might be better. meh.

MethodMeanErrorStdDevGen 0Gen 1Gen 2Allocated
NormalListAndAdd83.12 ns1.614 ns1.585 ns0.1913--184 B
ListAndArray232.13 ns3.011 ns2.669 ns0.3245--312 B
ListAndArrayBuffer604.80 ns9.204 ns8.159 ns0.6399--616 B
ListAndArrayBufferWithLocalFunction653.07 ns14.461 ns13.527 ns0.6399--616 B

About

Just use Span<T> if you can. I couldn't.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages