Java reduce allocated memory

Trying to reduce memory allocations in java game — for iterator

Occasionally my game has hicups/dropped frames because of garbage collection. So I am trying to reduce this by removing unnessasary allocations. Using the allocation tracker in Eclipse I see that my code below:

for (IGameObject obj : mObjects) < //stuff >
java.util.ArrayList$ArrayListIterator 24 bytes java.util.ArrayList iterator 

I can easily change all places where this is happening as mObjects is an ArrayList . Just out of interest though, will proguard or jit somehow optimise this to a basic for loop? As it seems a shame I have to make my code more verbose to avoid this allocation.

Is it 24 bytes worth an optimization? even if you allocate it for 1000 times its only 23.5KB. I thinkyou should look at your graphics or other heavy objects!

@Tecigo As they say, it’s not the size that counts. Garbage collection during the game causes hicups/dropped frames. Best solution is to remove unnessasary allocations, this is just one of many allocations I’m trying to remove.

2 Answers 2

Well, as people have said, don’t optimize unless it’s really an issue, but there’s always:

int sz = mObjects.size(); IGameObject gameObject = null; for (int i=0;i

In this case you’re just looping through by index. For ArrayList this is pretty efficient (as efficient as an iterator probably from a speed standpoint). However, if you drop in a LinkedList at some point instead, it goes to hell for large lists, as .get(index) is terribly inneficient for LinkedList.

Читайте также:  Python selenium получить все ссылки

I would not worry about the extra 24 bytes unless you really have memory issues.

The best way to control the memory consumption is to do the allocations yourself and in basic structures.

For example you could transform your ArrayList mObjects in a simple array IGameObject[] mObjects = new IGameObject[MAX_GAME_OBJECTS]; (you should know/compute what is the maximum number of objects your game can handle). In addition you should re-use the objects. You could keep an array boolean[] isObjAlive = new boolean[MAX_GAME_OBJECTS]; (same dimension as mObjects) and it will help in the first place to know which objects you no longer display and in the second, if the object is reusable:

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Reducing memory consumption in Java [closed]

I have worked with some projects where achieving better performance and reducing memory consumption has been the primary goal. But believe me it has already been hard to control the memory consumption in Java. This wiki page, says on «Java Program Speed» Java is in some cases equal to C++ on low-level and numeric benchmarks. These statistics do not really show a major difference in time computation Performance benchmark. However, the memory usage in Java is quite higher than C++, since there is an 8-byte overhead for each object and 12-byte for each array in Java (32-bit; twice as much in 64-bit java) as mentioned in above wiki link. Now the question is what all measures people take to minimize the memory utilization in Java? Please note that I am much concerned about memory than performance, since I cannot think of any better ways than «writing better programs» and «correctly tuning memory in JDK»

You can’t optimize memory footprint as well in java as you can in c++. If memory is the main constraint, is there a reason you need java?

Java uses 4 more bytes for the header of an object in a 64-bit program which is not double. Java typically uses 32-bit references for up to 32 GB in a 64-bit JVM, while C/C++ 64-bit programs typically use 64-bit pointers.

+Anshu Java philosophy really don’t cares how much RAM Is used, the big point for Java is scalability, performance and standardization, If you want something with the most of Java advantages but lightweight consider take a look at GOLANG that is the middle between Java and C++

If configured properly, JVM can be scaled vertically optimizing memory usage to the current load. The selected garbage collector is one of the main foundational bricks and its settings can influence the whole project. Use G1 GC and avoid «aggressive heap» approach. More specifics are in the article «Minimize Java Memory Usage with the Right Garbage Collector» javacodegeeks.com/2017/11/…

4 Answers 4

Depending on your what you are working on you can benefit from different programming practices such as:

  • Limiting the amount of variables that you initialize way before actually using them.
    • Just a general good coding tip. A variable that has been initialized and isn’t needed for awhile is holding on to memory that isn’t needed yet which may be wasting resources.
    • I’ve used this before in reflection heavy applications where I need to get the list of members on an object within a loop and it can help performance considerably depending on the situation where it may be needed.
    • http://www.javaworld.com/jw-06-1998/jw-06-object-pool.html
    • http://www.ibm.com/developerworks/library/j-jtp0730/

    Object pooling (and by extension and to an even greater degree, thread pooling) actually tends to increase memory usage, in order to improve performance. The whole point of it is that you hold on to objects you’re not using at the moment, under the assumption that you’ll need them again soon.

    Good catch and absolutely right. It should be used carefully and situationally based on the needs of the application. It may improve performance but it does tend to increase memory usage. It typically is used in fast paced processing applications such as games, etc. The same can be said of thread pooling.

    Actually, it’s not quite as black and white as that. Object pooling can reduce the memory footprint in certain situations where you create a lot of objects , use them briefly and then discard them. When you’re doing this all of the time, you’ll not only incur a GC overhead, but there’s every chance that the GC won’t be able to keep up with the pace of it. So for that reason it might be better to have a small pool of reusable objects than to keep creating new ones.

    There can be two motivation for managing memory in java.

    1. Avoiding frequent creation/deletion of objects.

    This in turn avoids GC from waking up very often as this can cause one or more of your executing threads to suspend.

    Avoid temporary/permanent memory holes

    2. Reduce the overall memory consumption of VM

    This will be needed if your VM will be running in an environment where you have stringent memory constraints.

    Ideally from memory perspective a well written java program should try and achieve both of the above. Now to achieve 1 you should do the following.

    • Prefer static memory allocation, i.e allocate once per VM as opposed to dynamic memory allocation.
    • Avoid creation of temporary objects within functions, to do this most objects can implement a reset() method which can allow the object to reused
    • Understand which API you are using, eg. if you use String, you will
      end up creating as many instances as there are modifications. The same applies for auto boxed types.

    The above points also help in managing or controlling point 2

    To keep a check on VM memory size, you need to do the above mentioned points and also do the following

    Use Xmx and Xms flags while launching your VM and deliberately set their values to lower values than what might be needed and be on the lookout of OutOfMemoryError .

    If OutOfMemoryError happens which means you are over shooting the max VM size. Identify what is the cause and start tuning your object creation.

    There is not much you can do about memory other than reducing the number of objects you create and trying making your object short-live. However, Java will still use all the memory it is allowed for the best performance.

    what all measures people take to minimize the memory utilization in Java?

    They look at small benchmarks rather than micro-tests of how large an array is.

    You can try comparing Java’s references (which uses 4-bytes even on a 64-JVM) to C++ shared pointers (which can use 48-bytes on a 64-bit process) and come to some conclusion which is unlikely to be useful in a real program.

    I am much concerned about memory than performance, since I cannot think of any better ways than «writing better programs» and «correctly tuning memory in JDK»

    Usually all you need do is use a memory profiler. This will help you minimize memory consumption in Java.

    I find this obsession with saving every byte is anachronistic in most cases. In a PC, one byte of memory costs around 5e-7 cents. Or about 2e-6 seconds of your time. These can add up but if you only save 100 KB, it may not be worth changing any code to do it and if you are going to save 1 GB, it may be worth spending a couple of hours on it. Even if you do save 1 GB, the memory is reusable, but your time is not.

    «If memory is the main constraint, is there a reason you need java?»

    I agree with this point that if you have a device with a few MB, i.e. smaller than android phone for example, C would be your best choice. If you have a device which at least a smart phone capacity, it may be that Java is fine for your needs.

    Источник

Оцените статью