I’m building a message router and would like it to be as fast as possible.
I want to stay within c# 4.0 and want to use sockets as fast as possible.
I may not need to bring all the data into managed memory.
I am dealing with byte arrays and am bringing the data into managed memory using this method (unless a better option is found): http://www.codeproject.com/KB/cs/ReadingStructuresEmit.aspx
Questions:
1) Is there a performance gain by using sockets in unsafe? how much?
2) Is there a pinvoke or data marshaling hit when using an unsafe method like this (with all structs unsafe as well)
public unsafe partial class Native
{
[DllImport("Ws2_32.dll")]
public static extern int connect(SOCKET s, sockaddr_in* addr, int addrsize);
}
3) For #2, does it matter if the data processing happens in unsafe and when the unsafe method returns no data is returned (so maybe nothing is marshaled into managed)?
These kind of improvements just cannot have any measurable effect. The real work is done in kernel mode, the many layers in the TCP/IP driver stack. Lots of code there wants to take a sniff of the IRP packets. And ultimately it hits the NIC. That’s where the real throttling happens. A one gigabit Ethernet interface is the common high end. That’s peanuts compared to the rate at which a CPU can shovel data around. Even the slow RAM bus can easily move data 40 times faster. Not to speak of the latency involved with actually making a connection once it hits the network.
These paths are taken by ws2_32.dll as well as System.Net. You ought to measure it. My prediction is that you can’t see a signal over the noise.