views:

85

answers:

3

I'm playing around with creating a source code generator for C# (.NET). Will generating properties or methods that never get called cause my code to run slower? How about inserting "using" statements for libraries that don't get used?

I'm assuming the compiler is smart enough not to build in the unused "using" statements, but there is no way for it to know about properties and methods since they could be inserted for external applications to use.

+5  A: 

Unused methods will make the executable slightly larger. It will take a bit longer to load, and will consume more system memory.

If the application runs in a memory constrained environment you may see a slight reduction in performance.

Aside from that, you should not see a performance slowdown.

The "using" statements just allow you to write shorter versions of class names in your source code. They do not impact the file size or execution speed.

There are third party linkers that can remove unreferenced methods from a final .EXE.

Eric J.
+3  A: 

You should consider using partial methods, especially when using code generators. A partial method, if it's not actually implemented, will be removed by the compiler.

Randy Minder
+1 Thanks for the suggestion. That should come in handy as I continue with this project.
Rick
+3  A: 

The compiler is already smart enough to only list referenced assemblies in the final executable that are actually used. No need to fiddle with assembly references or using directives.

The JIT compiler will only ever generate code for methods that are actually called. So you will not have any machine code or compile time overhead due to code that is never used.

Your executable image is getting referenced through a memory-mapped file by the CLR. RAM will only be used if actual content in the DLL is used by the CLR. It depends how the IL of the methods you use is distributed through the image. There are reasonable odds that since the JIT compiler never references the IL, the image data won't be paged into RAM either. In other words, you'll lose some virtual memory space but won't consume a corresponding amount of RAM.

If your DLL is strong named and stored in a non-trusted location then the warm boot time will be slightly longer due to the larger file size.

Hans Passant
The IL code will still be present in the EXE/DLL though, won't it? Otherwise it would not be possible to dynamically load an assembly or invoke a method through reflection. That's a good point (+1) that unused IL code will only occupy physical memory if it's on a page that also contains referenced code. Whether or not physical memory is used depends on the interleaving of referenced and non-referenced methods.
Eric J.
That is correct.
Hans Passant