代码优化-未使用的方法
我如何判断某个方法是否永远不会被使用?
我知道对于 dll 文件和库,您无法真正知道其他人(另一个项目)是否会使用这些代码。
一般来说,我认为任何公共的东西都可能在其他地方使用。
但是私有方法呢?是否可以安全地假设,如果我没有看到对该方法的显式调用,则不会使用该方法?
我认为对于私有方法更容易决定。但仅针对私有方法来决定是否安全?
How can I tell if a method will never be used ?
I know that for dll files and libraries you can't really know if someone else (another project) will ever use the code.
In general I assume that anything public might be used somewhere else.
But what about private methods ? Is it safe to assume that if I don't see an explicit call to that method, it won't be used ?
I assume that for private methods it's easier to decide. But is it safe to decide it ONLY for private methods ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
取决于语言,但通常不使用在程序中出现一次且不公开/导出的名称。也有例外,例如构造函数和析构函数、运算符重载(在 C++ 和 Python 中,定义点的名称与调用站点的名称不匹配)以及各种其他方法。
例如,在 Python 中,要允许索引 (
foo[x]
) 工作,您可以在foo
所在的类中定义一个方法__getitem__
。属于.但您几乎不会显式调用__getitem__
。Depends on the language, but commonly, a name that occurs once in the program and is not public/exported is not used. There are exceptions, such as constructors and destructors, operator overloads (in C++ and Python, where the name at the point of definition does not match the name at the call site) and various other methods.
For example, in Python, to allow indexing (
foo[x]
) to work, you define a method__getitem__
in the class to whichfoo
belongs. But hardly ever would you call__getitem__
explicitly.您需要了解的是代码的(或所有可能的)入口点:
您需要做是递归地跟踪所有入口点的所有引用以标记所有使用的方法。任何未标记的内容都可以安全地 - 并且应该 - 被删除。
由于这是一项勤奋但例行的工作,因此有可用的工具可用于各种编程语言。示例包括用于 C# 的 ReSharper 或 ProGuard 适用于 Java。
What you need to know is the (or all possible) entry point(s) to your code:
What you need to do is follow all references from all entry points recursively to mark up all used methods. Whatever remains unmarked can safely - and should - be removed.
Since this is a diligent but routine piece of work, there are tools available which do that for various programming languages. Examples include ReSharper for C# or ProGuard for Java.