Will the compiler only compile code that can get executed?

后端 未结 6 1952
梦谈多话
梦谈多话 2020-12-15 03:37

I have a class library and am using only part of it. Is there a need to delete what isn\'t being used in order to shrink the size of the created code (in release configurati

相关标签:
6条回答
  • 2020-12-15 03:42

    Determining all and only dead code is (if one makes the idealization that one has a "math world" like language) recursively undecidable, in most languages. (A few rare ones like the Blaise language are decidable.)

    0 讨论(0)
  • 2020-12-15 03:48

    No, the compiler includes the "dead" code as well. A simple reason for this is that it's not always possible to know exactly what code will and won't be executed. For example, even a private method that is never referenced could be called via reflection, and public methods could be referenced by external assemblies.

    You can use a tool to help you find and remove unused methods (including ones only called by other unused methods). Try What tools and techniques do you use to find dead code? and Find unused code to get you started.

    0 讨论(0)
  • 2020-12-15 04:01

    I doubt the compiler will remove anything. The fact is, the compiler can't tell what is used and what is not, as types can be instantiated and methods called by name, thanks to reflection.

    0 讨论(0)
  • 2020-12-15 04:04

    Let's suppose there is a class library called Utility. You created a new project and added this class library to that project. Even if your EXE calls only 1-2 methods from the class library, it's never a good idea to delete the unreferenced code.

    It would go against the principle of reusablity. Despite the fact that there would be some classes present in the library unreferenced from the EXE, it would not have any bad impact on performance or size of the program.

    0 讨论(0)
  • 2020-12-15 04:05

    It all gets compiled. Regardless of whether it is called or not. The code may be called by an external library.

    The only way to make the compiler ignore code is by using Compiler Preprocessor Directives. More about those here.

    0 讨论(0)
  • 2020-12-15 04:08

    to the question of whether there is a "need to delete what isn't being used in order to shrink the size of the created code": i think this would only be useful to save network bandwidth. removing unused code is crucial in web applications to improve loading speeds etc.

    if you're code is an exe or a library, the only reason i see to remove dead code, is to improve your code quality. so that someone looking at your code 2 years down the line won't scratch their heads wondering what it does.

    0 讨论(0)
提交回复
热议问题