Friday, February 22, 2008

consider to use local variables in some cases

who said performance == performance?

If you visited this blog already you now that indeXus.Net Shared Cache Server part is developed now as an asynchronous server and not a thread per client model. One of the very central server methods is to receive data. For this we have the following one:
private void ReadCallback(IAsyncResult ar)

{
// some code int read = handler.EndReceive(ar);
if (read > 0)
{
Monitor.Enter(state);
for (int i = 0; i <>
{
state.DataBuffer.Add(state.Buffer[i]);
}
Monitor.Exit(state);
// .
// .
// .
// .
// some more code
}

The above loop is developed straightforward, take the received buffer and concatenate it to the actual List until you received all needed data from the client. Well done - works great - but its slow like hell !!!!

Lets do some re-factoring and save up to 2.5 sec. which is actually for the tested use case 27,2% of end-to-end time:
adding 1000 objects with approx. 100kb toke 10,251 sec. in average (100 runs) - after this change we ended up with 7,456 sec for the same case in average for also 100 runs.

private void ReadCallback(IAsyncResult ar)
{
// some code
int read = handler.EndReceive(ar);
if (read > 0)
{
Monitor.Enter(state);
// save 2.5 seconds while i copy data to local variables and i do not access the property
byte[] localBuffer = new byte[state.DataBuffer.Count];
localBuffer = state.Buffer;
List localList = new List();
localList.AddRange(state.DataBuffer);
// copy all buffer data into DataBuffer which is list and contains all data until we get the whole message.
for (int i = 0; i < read; i++)
{
localList.Add(localBuffer[i]);
}
state.DataBuffer = localList;
Monitor.Exit(state);
// .
// .
// .
// .
// some more code
}

My conclusion is simple, keep attention were do you access object properties. I'm pretty sure that in 99% of all use cases it would not matter but here, its an amazing result for today's session.

No comments:

Shared Cache - .Net Caching made easy

All information about Shared Cache is available here: http://www.sharedcache.com/. Its free and easy to use, we provide all sources at codeplex.

Facebook Badge