我计划通过以下方式在 Android (3.0) 中创建 2D(地形) map 的表示
- 类
MapCooperative
,它只是一个“结构体”,由 int 类型的公共(public)属性 x,y 组成,表示一个 MapCooperative - 类
MapPoint
(可能不是一个好名字),它封装了访问和更改 map 中某个点的数据(针对一个 map 坐标)的方法 一个类
Map
,它有一个实例/Map(我的应用程序中只有一个),并通过一个HashMap
封装了一个Map:public class Map { HashMap<MapCoordinate, MapPoint> mapPoint = new HashMap<MapCoordinate, MapPoint>(); }
所以,我的问题是:在 Android 上拥有许多(Java)对象实例对性能是否至关重要(只有平板电脑是我的应用程序的目标)。当然,这张 map 只是我整个应用程序的一小部分。 map 可能会变得相当大。
感谢您的反馈。
最佳答案
如果可能的话,您可以尝试实现Fly Weight模式。官方文档建议避免创建对象:
block 引用>Object creation is never free. A generational GC with per-thread allocation pools for temporary objects can make allocation cheaper, but allocating memory is always more expensive than not allocating memory.
If you allocate objects in a user interface loop, you will force a periodic garbage collection, creating little "hiccups" in the user experience.
Thus, you should avoid creating object instances you don't need to. Some examples of things that can help:
- When extracting strings from a set of input data, try to return a substring of the original data, instead of creating a copy. You will create a new String object, but it will share the char[] with the data.
- If you have a method returning a string, and you know that its result will always be appended to a StringBuffer anyway, change your signature and implementation so that the function does the append directly, instead of creating a short-lived temporary object.
A somewhat more radical idea is to slice up multidimensional arrays into parallel single one-dimension arrays:
- An array of ints is a much better than an array of Integers, but this also generalizes to the fact that two parallel arrays of ints are also a lot more efficient than an array of (int,int) objects. The same goes for any combination of primitive types.
- If you need to implement a container that stores tuples of (Foo,Bar) objects, try to remember that two parallel Foo[] and Bar[] arrays are generally much better than a single array of custom (Foo,Bar) objects. (The exception to this, of course, is when you're designing an API for other code to access; in those cases, it's usually better to trade correct API design for a small hit in speed. But in your own internal code, you should try and be as efficient as possible.)
Generally speaking, avoid creating short-term temporary objects if you can. Fewer objects created mean less-frequent garbage collection, which has a direct impact on user experience.
关于java - android 中很多对象实例是一个问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5008940/