哪些对象可用于 GC?

发布于 2025-01-17 01:35:01 字数 330 浏览 0 评论 0原文

我正在编写该程序,应该针对堆和 GC 的使用进行优化。基于此,我需要创建尽可能少的对象。所以我想知道如果我把命令写在一行中,是否会影响GC?

例如,这段代码创建了 2 个可用于 GC 的对象:

UUID uuid = UUID.randomUUID();
String s = uuid.toString();

如果我在一行中重写此代码,如下所示:

String s = UUID.randomUUID().toString();

第二个变体也会为 GC 创建 2 个对象还是仅创建 String 对象?

I am writing the program, which should be optimized for usage of heap and GC. Based on this I need to create as less objects as possible. So I am wondering if it is a matter for GC if I write the commands in one line?

For example this code creates 2 objects, which are avaliable for GC:

UUID uuid = UUID.randomUUID();
String s = uuid.toString();

What if I rewrite this code in one line, like this:

String s = UUID.randomUUID().toString();

Will the second variant also create 2 objects for GC or only the String object?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

潜移默化 2025-01-24 01:35:01

就 GC(或者实际上是 Java 的任何部分)而言,这两行之间没有任何区别。

需要担心堆的优化是很不寻常的。您是否有一个程序已经可以运行并且占用了太多堆,或者进行了太多 GC?如果没有,不用担心。这是过早的优化,可能会让事情变得更糟。 Java 的 GC 确实非常擅长它的功能。如果您不确定这两行之间的区别,那么您应该相信 Java 会处理它自己的内存使用情况。

There is no difference whatsoever between those two lines as far as the GC (or, really, any part of Java) is concerned.

It's very unusual to need to worry about optimizing for heap. Do you have a program that already works and takes too much heap, or does too much GC? If not, do not worry about it. This is premature optimization which will likely make things worse. Java's GC is really, really good at what it does. If you are not sure about the difference between those two lines, then you should trust Java to be take care of its own memory usage.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文