在java中的堆栈内存上创建对象? [英] Creating Objects on the stack memory in java ?

查看:625
本文介绍了在java中的堆栈内存上创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于好奇,这只是一个简单的理论问题。我一直都喜欢java风扇男孩。但有一件事让我想知道为什么java不提供在堆栈上创建对象的机制?如果我可以在堆栈而不是堆上创建小的Point(int x,int y)对象,就像在C#上创建结构一样,那会不会更有效率。在java中这个限制背后有什么特殊的安全原因吗? :)

This is just a simple theoretical question out of curiosity. I have always been like a java fan boy. But one thing makes me wonder why java does not provide mechanism for creating objects on the stack ? Wouldn't it be more efficient if i could just create small Point(int x,int y ) object on the stack instead of the heap like creating a structure on C# . Is there any special security reason behind this restriction in java ? :)

推荐答案

这里的策略是,不要将这个决定泄露到语言中,Java让JVM / Hotspot / JIT /运行时决定它想要分配内存的位置和方式。

The strategy here is that instead of leaking this decision into the language, Java lets the JVM/Hotspot/JIT/runtime decide where and how it wants to allocate memory.

正在进行研究以使用逃逸分析来确定哪些对象实际上不需要进行堆和堆栈 - 分配它们。我不确定这是否已经成为一个主要的JVM。但如果确实如此,它将由运行时(事物-XX:某事物)控制,而不是开发人员。

There is research going on to use "escape analysis" to figure out what objects don't actually need to go onto the heap and stack-allocate them instead. I am not sure if this has made it into a mainstrem JVM already. But if it does, it will be controlled by the runtime (thing -XX:something), not the developer.

这样做的好处是即使是旧代码也可以受益来自这些未来的增强功能,而无需自行更新。

The upside of this is that even old code can benefit from these future enhancements without itself being updated.

如果您想手动管理(但仍然让编译器检查它是否安全),请查看Rust。

If you like to manually manage this (but still have the compiler check that it stays "safe"), take a look at Rust.

这篇关于在java中的堆栈内存上创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆