dispose 方法的重要性 (libgdx)
Importance of the dispose method (libgdx)
我刚刚开始 Android 游戏开发,目前正在测试 libgdx Framework
。我只是想知道 dispose()
方法的重要性是什么以及为什么有必要处理那里的每个对象?只是为了节省资源?
欣赏。
Java 是一个 "managed language"。这意味着您在应用程序中使用的所有内容(例如 classes 或数组的实例)在您不再使用时都会自动销毁。这是由 "garbage collector" 完成的。所以,当你创建例如一个数组 (float[] arr = new float[1000];
) 然后你分配内存,但你永远不必自己释放内存,因为垃圾收集器会在你不再使用数组时为你做这件事 (arr
).
然而,在某些情况下,垃圾收集器不知道如何自动为您释放一些东西。例如,当您在视频内存 (VRAM) 中分配一些 space 时,您无法直接访问该内存,而是使用图形驱动程序来使用该内存。例如(伪代码):
byte[] image = loadImageFromDisk();
int vramId = graphicsDriver.allocateMemory(image.length);
graphicsDriver.copyToVRAM(vramId, image);
image = null;
...
// At this point the garbage collector will release the memory used by "image".
// However, the allocated VRAM still contains a copy of the image, so you can still use it.
...
graphicDriver.showImageOnScreen(vramId);
...
// The garbage collector can't free the VRAM though, you need to manually free that memory.
...
graphicsDriver.releaseMemory(vramId);
因此,实际上,在这种情况下有两种资源。
- 垃圾收集器将自动释放的资源。我们称之为:托管资源.
- 垃圾收集器无法自动释放的资源。我们称之为:原生资源.
正如您可能想象的那样,libgdx 在幕后使用了相当多的本机资源。为了正确管理这些资源,libgdx 包含 Disposable
接口。每个实现此 Disposable
接口的 class 都会(直接或间接)使用垃圾收集器无法自动释放的本机资源。因此,如果您不再需要这些 classes,您需要手动调用 dispose
方法。
不调用 dispose
方法可能会导致本机资源出现问题。例如。您可能 运行 可用视频内存不足或类似情况,导致您的应用程序崩溃或类似情况。这通常被称为 "memory leak".
我刚刚开始 Android 游戏开发,目前正在测试 libgdx Framework
。我只是想知道 dispose()
方法的重要性是什么以及为什么有必要处理那里的每个对象?只是为了节省资源?
欣赏。
Java 是一个 "managed language"。这意味着您在应用程序中使用的所有内容(例如 classes 或数组的实例)在您不再使用时都会自动销毁。这是由 "garbage collector" 完成的。所以,当你创建例如一个数组 (float[] arr = new float[1000];
) 然后你分配内存,但你永远不必自己释放内存,因为垃圾收集器会在你不再使用数组时为你做这件事 (arr
).
然而,在某些情况下,垃圾收集器不知道如何自动为您释放一些东西。例如,当您在视频内存 (VRAM) 中分配一些 space 时,您无法直接访问该内存,而是使用图形驱动程序来使用该内存。例如(伪代码):
byte[] image = loadImageFromDisk();
int vramId = graphicsDriver.allocateMemory(image.length);
graphicsDriver.copyToVRAM(vramId, image);
image = null;
...
// At this point the garbage collector will release the memory used by "image".
// However, the allocated VRAM still contains a copy of the image, so you can still use it.
...
graphicDriver.showImageOnScreen(vramId);
...
// The garbage collector can't free the VRAM though, you need to manually free that memory.
...
graphicsDriver.releaseMemory(vramId);
因此,实际上,在这种情况下有两种资源。
- 垃圾收集器将自动释放的资源。我们称之为:托管资源.
- 垃圾收集器无法自动释放的资源。我们称之为:原生资源.
正如您可能想象的那样,libgdx 在幕后使用了相当多的本机资源。为了正确管理这些资源,libgdx 包含 Disposable
接口。每个实现此 Disposable
接口的 class 都会(直接或间接)使用垃圾收集器无法自动释放的本机资源。因此,如果您不再需要这些 classes,您需要手动调用 dispose
方法。
不调用 dispose
方法可能会导致本机资源出现问题。例如。您可能 运行 可用视频内存不足或类似情况,导致您的应用程序崩溃或类似情况。这通常被称为 "memory leak".