是否有 Java 或 C# 的宏工具?

2022-01-11 00:00:00 inline macros c# java

宏很有用.

因此,我偶尔会感叹 Java 和 C# 中没有宏.宏允许我强制内联,但允许我使用非宏代码的代码可管理性.

Therefore, I occasionally bemoan the absence of macros in Java and C#. Macros allow me to force in-line but allow me the code-manageability of non-macro code.

是否有任何基于 Java 或 C# 的项目/产品有效地允许宏或指定内联扩展.

Is there any Java- or C#-based project/product somewhere out there that effectively allow macros or specifying in-line expansion.

我正在考虑类似的事情

@macro public void hello(int x){ ... }

@macro public void hello(int x){ ... }

或者当我调用一个方法时,调用前的@inline 注释会影响被调用方法的内联.

or when I call a method, an @inline annotation preceding the call would effect the called-method to be in-lined.

或者,我是否需要知道我应该相信编译器会为我做出最好的决定,即在最好的分析情况下,它可能会内联调用.

or, should I need to know that I should just trust the compiler to make the best the decision for me that at the best of its analysis it might in-line a call.

我希望这个问题不会导致争论宏的优缺点/有用性.

I hope this question will not lead to debating the pro/cons/usefulness of macros.

推荐答案

宏不是标准 Java 语言的一部分,我不知道主流 Java 工具、IDE 等是否支持任何宏预处理器.因此,如果您在 Java 代码中使用宏,您应该会体验到一些痛苦".例如,

Macros are not part of the standard Java language, and I'm not aware of any macro preprocessor being supported by mainstream Java tools, IDEs and so on. So if you use macros in your Java code you should expect to experience some "pain". For example,

  • 源代码调试器不允许您相对于原始源代码设置断点.
  • 如果您与宏共享 Java 代码,许多 Java 开发人员可能会对此嗤之以鼻,和/或抱怨必须安装/使用额外的工具.

Java 的第三方宏预处理器有很多例子;例如Jatha, OpenJava, PrintMacroJ、JavaMacros 等等...(但你有没有遇到过使用它们的项目?)

There are quite a few examples of third-party macro pre-processors for Java; e.g. Jatha, OpenJava, PrintMacroJ, JavaMacros, and so on ... (But have you ever come across a project that uses any of them?)

宏允许我强制内联,但允许我使用非宏代码的代码可管理性.

Macros allow me to force in-line but allow me the code-manageability of non-macro code.

没错.但是 JIT 编译器在确定 应该 内联的内容方面可能比您做得更好.它会(肯定地)知道这些块有多大,并且它会有关于执行频率、分支预测等的运行时统计信息,这些对你来说是不可用的.

True. But the JIT compiler can probably do a better job than you can in determining what should be inlined. It will know (for sure) how big the chunks are, and it will have runtime stats on execution frequency, branch prediction, etc that are not available to you.

请注意,有一些 Hotspot JVM 调优选项会影响优化器的内联决策;请参阅 此页面,并扫描inlin".例如,有一个似乎允许您增加内联方法体的大小上限.

Note that there are some Hotspot JVM tuning options that can influence the optimizer's decisions on inlining; see this page, and scan for "inlin". For instance, there is one that seems to allow you to increase the upper size threshold for an inlined method body.

相关文章