Thursday, January 8, 2009

Indexer example in C#

using System;
namespace Indexer
{
class Program
{
static void Main(string[] args)
{
TestObject obj1 = new TestObject();
TestObject obj2 = new TestObject();

obj1.AddData(new[] { "this", "is", "test", "one", "!?" });
obj2.AddData(new[] { "this", "is", "another", "test", "!" });

// output to check object
OutputObject(obj1, "OBJ1");
OutputObject(obj2, "OBJ2");

obj1[1] = "was";
obj2[1] = "used to be";

// output to check object
OutputObject(obj1, "OBJ1");
OutputObject(obj2, "OBJ2");
}

public static void OutputObject(TestObject obj, string name)
{
for (int i = 0; i < 5; i++)
Console.WriteLine(string.Format("{0}: {1}", name, obj[i]));
}
}

class TestObject
{
private readonly string[] store = new string[5];

public string this[int index]
{
get { return store[index]; }
set { store[index] = value; }
}

public void AddData(string[] objData)
{
for (int i = 0; i < 5; i++)
store[i] = objData[i];
}
}
}

Tuesday, January 6, 2009

Memory alignment

I have heard the discussion of memory alignment, or rather the question about is it really necessary. I can say from a standpoint of any system where you would like to carefully manage memory (for speed or scalability), yes, it matters.

Memory bandwidth can quickly become the bottleneck to a system. If we take, for instance, this case. We have a processor that has a memory width of 32 bits. If we are going to fetch something from memory (say an int, which happens to be 32 bits wide). With this situation, as it is aligned, the processor can fetch the value in one cycle.

Many of the data enumerations in DirectX contain a value at the end named x_FORCE_DWORD with a value of 0x7FFFFFFF. This value is 1111111111111111111111111111111 (31) bits. This will guarantee this enum will be at least 32 bits in size.