Java相当于register int?
在C中,我可以为变量分配一个寄存器,例如:
register int i = 0;
我知道Java是一种解释性语言,并且与CPU有很多抽象。
是否有任何机制可以请求(如果体系结构不允许,那又怎样)我的变量保留在寄存器中而不是移动到缓存或主内存?
我不认为有什么办法,但我以前就感到惊喜过。
谢谢你,
In C, I can allocate a register for a variable, for example:
register int i = 0;
I am aware that Java is an interpreted language, and is many many abstractions away from the CPU.
Is there any mechanism available to even request (and if the architecture doesn't allow it, so what) that my variable remains in a register instead of moving to cache or main memory?
I don't suppose there is any way, but I have been pleasantly surprised before.
Thank you,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
C 中的
register
不会将变量注册。 它只是给编译器提示,最好将其放入寄存器中。在 Java 中没有等效的。
register
in C does not put a variable to register. It simply gives the compiler the hint, that it would probably be good to put it into a register.In Java there is no equivalent.
如果它在很短的空间内使用得足够多,值得将其设为寄存器 int,那么热点编译器应该能够自行解决这一问题。
事实上,热点编译器应该能够比 C/C++ 编译器做得更好,因为它有更多的信息可供使用。 C/C++ 编译器必须猜测; HotSpot 可以测量。
If it's used enough in a short space that making it a register int would be worthwhile, then the hotspot compiler should be able to figure that out itself.
In fact, the hotspot compiler should be able to do a better job than the C/C++ compiler, because it has more information to work with. C/C++ compilers have to guess; HotSpot can measure.
Java 中没有类似的东西。 即使在 C 中,也不能保证变量将存储在寄存器中,并且编译器可以随意忽略它。
在Java中,该方法将被解释,直到热点JIT启发式地确定它需要编译。 对于编译代码,它使用着色算法将变量和临时值分配给寄存器,或者在寄存器溢出的情况下写入 RAM 或从 RAM 写入。
There's no equivalent in Java. Even in C there is no guarantee that the variable will be stored in a register and compilers are free to ignore it.
In Java, the method will be interpreted until the hotspot JIT heuristically determines that it needs to be compiled. For compiled code it uses a coloring algorithm to assign variables and temporary values to registers, or write to/from RAM in the case of register overflow.
不,在 Java 中没有办法请求这个。 但是,您可以执行一些操作来阻止使用寄存器,例如对成员变量应用
易失性
修饰符。No, there's no way to request this in Java. However, there are some things that you can do that will prevent a register from being used, such as applying the
volatile
modifier to a member variable.你几乎在那里回答了你自己的问题:-)
但说真的,一般来说,尽可能清晰、简单地编写你的代码,JVM 将尽其所能正确处理你的代码。
You pretty much answered your own question there :-)
But seriously, in general, write your code as clearly and simply as you can, and the JVM will do what it can to treat your code right.
你可以创建一个名为@register的注解,但JVM肯定会忽略它。
例如
You can create an annotation called @register but the JVM will definitely ignore it.
e.g.