How to create an extremely effective function

I am developing a function (Java method) that will execute 40-80 times per second on a mobile device.

I want to avoid creating tons of dead variables that the GC collects as the function launches (possibly throughout the life of the application).

In C, I can use volatile , for example, to prevent the allocation of memory by my variables each time the function is executed ... I want to do something similar in Java, but I don’t know how to do it.

The function stores data in

  • 1 row
  • 4 integers
  • 2 1-dimensional array of strings

In general, in Java, what is the preferred method to use the above variables, but not redistribute them every time my function is executed (40+ times per second)?

Member elements will work, but is this the best solution?

Thanks! Brad

+6
java optimization memory-management
source share
5 answers
  • Wrap these fields in a class {Java likes to see an object} and select it once and use it.
  • Remember the concept of a string pool as you have an array of strings
+3
source share

Static member vars, they will not be unloaded until the class is unloaded. Keep in mind that if all references to a class are lost, it is possible that it may be GC'ed. I doubt it will be a problem in your case, however it is worth noting. In addition, if you create new class instances containing static vars members, you will be in the same boat from the distribution position.

+1
source share

I completely agree with this answer.

Each call to your function allocates more memory if you create variables on the fly, since the Java GC is not completely cleared until destruction is called when the class is deleted.

But if you are going to call the function several times, then their class member variables will simply be executed.

0
source share

Static variables can be used for this, but it is assumed that these variables are constants or that changes to them do not affect other threads that currently call the same function.

If your code needs to be reentrant, and static variables are not an option, you can create a simple data storage object that contains these variables and pass it as an argument to your function. Your calling environment may decide whether to pass these objects or not.

0
source share

Use either static class classes, or if you are going to create only one instance of a class, regular member variables will work.

If you need to modify the contents of a String, try using a StringBuilder instead of the immutable String instances that / gc 'ed will create.

ints are primitives, so they are not a problem.

String arrays will be fine, but think about what you put into them. Are you building new String objects and putting old gc?

0
source share

All Articles