Reading text files using pointers?
From: Einar Høst (anonymous_at_discussions.microsoft.com)
Date: 02/12/04
- Next message: Stu Smith: "Re: 12.34f vs (float) 12.34"
- Previous message: _e_: "DataGrid "MappingName" property"
- Next in thread: Einar Buffer: "Re: Reading text files using pointers?"
- Reply: Einar Buffer: "Re: Reading text files using pointers?"
- Reply: Jon Skeet [C# MVP]: "Re: Reading text files using pointers?"
- Messages sorted by: [ date ] [ thread ]
Date: Thu, 12 Feb 2004 03:46:33 -0800
Hi,
I'm trying to learn a bit about performance, hope someone can help me out.
I have a text file with 8-bit characters in it. In order to improve performance, I'm using a BinaryReader instead of a StreamReader. I've made two versions of my method, one which uses typesafe code, and one which uses unsafe code with pointers. I've read several places that direct pointer access will eliminate bounds-checking when accessing an array, and would like to see the effect myself. However, the typesafe code is as fast or faster than the unsafe code. The methods are practically identical, except for the access bit:
Shared code:
BinaryReader reader = ... // Open data reader.
int fileSize = ... // Get size of file.
int bufSize = 32768;
byte[] buf = null;
int bytesRead = 0;
int totalBytesRead = 0;
byte msgStartCode = (byte) '$';
Typesafe version is like:
do
{
buf = reader.ReadBytes(bufSize);
bytesRead = buf.Length;
totalBytesRead += bytesRead;
for (int bufIndex = 0; bufIndex < buf.Length; bufIndex++)
{
if (buf[bufIndex] == msgStartCode)
{
// Parse message.
}
} // for
} while (totalBytesRead < fileSize);
wheras the unsafe version is like:
do
{
buf = reader.ReadBytes(bufSize);
bytesRead = buf.Length;
totalBytesRead += bytesRead;
// Pin memory.
fixed (byte* bufPtrUnsigned = &buf[0])
{
sbyte* bufPtr = (sbyte*) bufPtrUnsigned; // Use to build message string
for (int bufIndex = 0; bufIndex < buf.Length; bufIndex++)
{
if (buf[bufIndex] == msgStartCode)
{
// Parse message, using e.g. new String(bufPtr, bufIndex, msgLength);
}
} // for
} // fixed
} while (totalBytesRead < fileSize);
Shouldn't the last version be faster?
Thanks in advance for any help!
- Next message: Stu Smith: "Re: 12.34f vs (float) 12.34"
- Previous message: _e_: "DataGrid "MappingName" property"
- Next in thread: Einar Buffer: "Re: Reading text files using pointers?"
- Reply: Einar Buffer: "Re: Reading text files using pointers?"
- Reply: Jon Skeet [C# MVP]: "Re: Reading text files using pointers?"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|