开发者

How to design extremely efficient function

I am designing a function (Java method) which will be executed 40-80 times per second on a mobile device.

I want to avoid producing a ton of dead variables which get collected by GC, as the function runs (possibly throughout the life of the app).

In C I might use volatile for example, to prevent the memory allocation of my variables in each execution of the function... I want to do something similar in Java 开发者_开发百科but don't know how.

The function stores data in

  • 1 string
  • 4 integers
  • 2 1-dimensional String arrays

In general, in Java, what is the preferred method for using the above variables but not re-allocating them every time my function is executed (40+ times per second)?

Member variables would "work" but is this the best solution?

Thanks! Brad


  • Wrap those fields in a class {Java loves to see the Object} and allocate it once and use it.
  • keep string pool concept in mind as you have String array


Static member vars, they won't get unloaded until the class is unloaded. Keep in mind that if all references to the class are lost it is possible that it can be GC'ed. I doubt that will be an issue in your case however it is worth noting. In addition if you are creating new instances of the class containing the static members vars you will be in the same boat from an allocation stance.


I totally agree with that answer.

Every call to your function would allocate more memory if your creating the variables on the fly as Java's GC doesn't fully clean up until destroy is called when the class is being disposed.

But if your going to be calling the function multiple times then just making them member variables of the class would also work.


You could use static variables for this, but that assumes that these variables are constants or that changes to them to not badly influence other threads currently calling the same function.

If your code must be reentrant and static variables are not an option, you can create a simple data-holder object which holds these variables and pass it as argument to your function. Your calling environment can decide whether to share these objects or not.


Use either static class fields, or if you are going to create only one instance of your class normal member variables will work.

If you need to change the contents of the String consider using a StringBuilder instead of immutable String instances that will be created/gc'ed.

int's are primitives, so they are not a problem.

Your String arrays will be okay, but think about what you are putting into them. Are you constructing new String objects and letting old ones gc?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜