Re: readonly arrays
- From: "Family Tree Mike" <FamilyTreeMike@xxxxxxxxxxxxxxxx>
- Date: Tue, 18 Nov 2008 19:09:37 -0500
"Family Tree Mike" <FamilyTreeMike@xxxxxxxxxxxxxxxx> wrote in message news:uM1I2ldSJHA.4916@xxxxxxxxxxxxxxxxxxxxxxx
"Mark" <mmodrall@xxxxxxxxxxxxx> wrote in message news:FE288528-7025-4E67-BCFF-DFCB4820A71F@xxxxxxxxxxxxxxxxI've been reading many of the articles on why C# doesn't have true readonly
arrays and I was doing a little time testing.
I found the ReadOnlyCollection<T> = Array.AsReadOnly<T>(T[]) construct but
when I ran some time tests, I was appalled to see that simple read access was
between 8x and 9x slower than just using a regular array (for type char
anyway).
I threw together a simple wrapper:
public class RArray<T>
{
private T[] holdme;
public RArray(T[] init)
{
holdme = (T[])init.Clone();
}
public T this[int i]
{
get { return holdme[i]; }
set { throw new InvalidOperationException("No way"); }
}
}
And the same timing test had my wrapper at around 75% slower.
Using Reflector, I looked at ReadOnlyCollection<T>'s get method and saw it
was doing essentially the same thing my wrapper was, so I couldn't explain
why ReadOnlyCollection<T> was just so much slower.
Any ideas?
Thanks
Mark
I only get a factor of slightly more than two using the following test code:
class Program
{
static int ListSize = 10000000;
static int [] SearchIDs;
static char [] OriginalArray;
static ReadOnlyCollection<char> ROC;
static void Setup()
{
Random r = new Random();
OriginalArray = new char[ListSize];
SearchIDs = new int[ListSize];
for (long idx = 0; idx < ListSize; ++idx)
{
OriginalArray[idx] = (char) r.Next();
SearchIDs[idx] = r.Next(ListSize);
}
ROC = Array.AsReadOnly<char>(OriginalArray);
}
static long TimeTestNormal()
{
char val;
Stopwatch sw = new Stopwatch();
sw.Start();
foreach (int idx in SearchIDs)
val = OriginalArray[idx];
return sw.ElapsedMilliseconds;
}
static long TimeTestRO()
{
char val;
Stopwatch sw = new Stopwatch();
sw.Start();
foreach (int idx in SearchIDs)
val = ROC [idx];
return sw.ElapsedMilliseconds;
}
static void Main(string[] args)
{
Setup();
Console.Out.WriteLine(string.Format("Test Normal: {0} milliseconds.", TimeTestNormal()));
Console.Out.WriteLine(string.Format("Test Read Only: {0} milliseconds.", TimeTestRO()));
Console.In.ReadLine();
}
}
And yes, I know the initialization of the random character array is far from a good way to do that, but, it does not affect the timing...
.
- Follow-Ups:
- Re: readonly arrays
- From: Mark
- Re: readonly arrays
- From: Mark
- Re: readonly arrays
- References:
- readonly arrays
- From: Mark
- Re: readonly arrays
- From: Family Tree Mike
- readonly arrays
- Prev by Date: Re: memory mapped file
- Next by Date: RE: App configuration for a service when running multiple instance
- Previous by thread: Re: readonly arrays
- Next by thread: Re: readonly arrays
- Index(es):
Relevant Pages
|