I can’t help but wonder if namespaces or project folder structure effect the performance of the assembly. My gut says “no, but it may possibly effect compile time”.
Thinking about performance always get’s in the way, especially if you’re a novice. I can’t help it! So, I thought I’d ask my fellow game developers who I respect and admire.
Everyone has explained how premature optimization is a bad idea (which it is): however I will explain why it actually makes no difference whatsoever (except for cases where you use reflection – more on that later).
Static Reference In Code
The CLR (and therefore MSIL – which is what C# compiles to) actually has no notion or concept of namespaces. A type (class, enum, etc.) is referred to by its full name (e.g.
System.Runtime.Serialization.ISerializable) and ‘full stops’ are just as opaque (meaningful) as any other character in the name. The whole concept of namespaces is something that C# (or whichever language you are using) provides for you. However, in terms of raw MSIL the type name doesn’t actually matter either.In MSIL you never refer to something by its name. Everything in an assembly (dll or exe) has a certain type of handle. For example a type has a
TypeHandleand anything contained by a type has aMemberHandle: both are a 32bit integer. So when you call a method you don’t writecall <MethodName> on <TypeName> in <Assembly>in MSIL – instead you writecall <MethodHandle> on <TypeHandle> in <Assembly>. Therefore getting a type that has 5000 characters in its name takes the same amount of time that one with 5 would. The actual names are stored in a separate place in the assembly: only so that you can use reflection to get them, or for compilers (in other words the names are only stored “for your information”) – this is called the metadata.I think there is a way to get ILDASM to give you the raw MSIL – but I am not sure.
Accessed Using Reflection
Because you are doing a string comparison between the type name you want and the names available in the assembly it makes a difference: string comparisons are a O(n) operation. However, this time is miniscule compared to the total cost of reflection and is completely negligible (it will make nanoseconds of a difference) – don’t even worry about it.
Summary
This is why premature optimization is really bad – you assumed this was a bottleneck where in reality there is no faster or slower way to do it.