0

I have a C# game server that creates a new object for every packet it receives that it then fills from the datasteam. After recently benchmarking it, I notice the line that does

 var packettype = Opcodes[opcode];
 var packet = (Packet)Activator.CreateInstance(packettype.Type);

is consuming the most resources of the whole application after profiling.

Changing everything to struct and creating a cached table of the empty packet bodies seems like it might work but a lot of redesign might be needed.

Anyone know a good way to really reduce the CPU usage of this, I was thinking keeping a instantiated object in the Opcodes table and then somehow copying it instead of instantiating a new object for each packet?

A lot of the packets are lightweight, but some are really large, having multiple fields and lists.

Note: Each packet is created 100% exactly the same before being filled.

Vans S
  • 1,743
  • 3
  • 21
  • 36
  • Before diving into a re-write I'd try to profile by packet type to limit what you need to optimize. – Chris Aug 17 '13 at 16:23
  • 2
    Have you tried creating the packets directly instead than using `CreateInstance`? I.e. with a switch statement that explicitly checks which type of packet to create and then executes a `new SpecificPacket()`? – MiMo Aug 17 '13 at 16:25
  • Also, I'm not sure if the profiler would show it or not in this case, but is there anything slow about the constructors of your various derived classes of `Packet`? – Joe Aug 17 '13 at 16:29
  • MiMo. That is possible but is CreateInstance really that resource hungry? I assume the large packets are slow to construct I guess that would be good to benchmark. – Vans S Aug 17 '13 at 16:55
  • http://stackoverflow.com/questions/6582259/fast-creation-of-objects-instead-of-activator-createinstancetype/16162809#16162809 Found answer here. – Vans S Aug 17 '13 at 16:59

0 Answers0