Skip to content

Instantly share code, notes, and snippets.

@redknightlois
Created September 1, 2014 04:47
Show Gist options
  • Save redknightlois/dfd16d3dd3f79f50cdc6 to your computer and use it in GitHub Desktop.
Save redknightlois/dfd16d3dd3f79f50cdc6 to your computer and use it in GitHub Desktop.
ArraySegment<T> performance on tight-loops
static float[] data = new float[1000000];
static void Main(string[] args)
{
int offset = 49421;
Stopwatch watch = new Stopwatch();
watch.Start();
float t = 0;
for (int tries = 0; tries < 1000; tries++)
{
for (int i = 0; i < 100000; i++)
{
t = data[i];
}
}
Console.WriteLine("Access without offset: " + watch.ElapsedMilliseconds + "ms.");
// Avoid the read optimization;
Console.WriteLine(t);
watch.Restart();
for (int tries = 0; tries < 1000; tries++)
{
for (int i = 0; i < 100000; i++)
{
t = data[offset + i];
}
}
Console.WriteLine("Access via offset: " + watch.ElapsedMilliseconds + "ms.");
// Avoid the read optimization;
Console.WriteLine(t);
var segment = new ArraySegment<float>(data, offset, 100000);
watch.Restart();
for (int tries = 0; tries < 1000; tries++)
{
for (int i = 0; i < 100000; i++)
{
t = data[i];
}
}
Console.WriteLine("Access via array segment: " + watch.ElapsedMilliseconds + "ms.");
// Avoid the read optimization;
Console.WriteLine(t);
Console.ReadLine();
}
@redknightlois
Copy link
Author

Access without offset: 120ms.
Access via offset: 118ms.
Access via array segment: 118ms.

@wesnerm
Copy link

wesnerm commented Nov 27, 2017

You made a mistake. You need to index segment instead of data. Indexing segment requires a cast to IList.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment