Memory optimalization in Java – tips and tricks


The memory can be filled very quickly when you use many objects. That’s why it is necessary to think where you create your objects and what kind of objects you create.

Long vs long or Integer vs int

Long is the object type of long. It’s possible to create Long with the value null. A long is a number of 64 bits. So it’s no object but just a number that require a valid number or 0 (it cannot be null).

The same matters for Integer vs int. An Integer is an object and an int is a 32-bit number.

When you just need numbers, it’s better to use a long or int. Sometimes numbers in a database are null, then it is required to use a Long or Integer otherwise you get a NullPointerException.

A Long or Integer vs a long or int take needs more memory.

Creating objects in a loop

There’s nothing so bad then creating objects in a for-, while- or do-while- loop. Every object you create in a loop will be recreated every time the loop loops and all these objects will be saved in the memory. If you have a loop that loops a 100 times, and you create an object inside that loop, you get 100 new objects.

for(int i = 0; i < 100; i++) {
    String str = "I am number " + i;

In the example above, you will generate 100 String objects. Each string will be recreated and saved in the memory. An optimization can you see below.

String str;
for(int i = 0; i < 100; i++) {
    str = "I am number " + i;

In this case, the String object will only be created once. Now, the loop will not recreate a new String-object, but will override the object. So in this case you only have 1 object.

Add comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Tag Cloud


%d bloggers like this: