Created
September 1, 2014 04:47
-
-
Save redknightlois/dfd16d3dd3f79f50cdc6 to your computer and use it in GitHub Desktop.
ArraySegment<T> performance on tight-loops
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
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
Access without offset: 120ms.
Access via offset: 118ms.
Access via array segment: 118ms.