Jump to content
  • Advertisement
Sign in to follow this  
Pufixas

Adding strings in Java creates new objects? (Strange hiccups in android game)

This topic is 2042 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

So I'm making a game for Android platform which uses Java for programming. I'm near the end of finishing it, but I noticed that it has very strange hiccups (60-70ms) every 3-4 seconds periodically. And I put timers all inside my code, deleting something, and checking what could cause this.

Then I found it, it would look something like this (but not exactly like this, but the principle is exactly the same):

 

String str = "FPS: " + fps + " score: " + currentScore;

 

 

The currentScore variable changes everyframe. 

 

After deleting this line of code, my game stops lagging!

The only thing I could think of is that adding two or more String objects with variables in Java will create new String object, then if my game runs at 80FPS that would be 80 String objects every second, and then the garbage collector comes in and collects all unused strings, while blocking my thread.

 

So after all this, my question would be is it true that adding variables to String objects in Java will create garbage? If so, is there any way to add them without creating any garbage?

Edited by Edvinas Kilbauskas

Share this post


Link to post
Share on other sites
Advertisement

You should use the StringBuffer(threadsafe) or StringBuilder(not threadsafe, usually faster than StringBuffer) class instead, Strings in Java are immutable and cannot be modified (any operation that modifies strings will create a new string (This is both slow and can trigger garbage collection). alternativly keep the constant parts of the text as separate strings and print them after eachother.

 

Quick, short and to the bullseye answer! Thanks!  

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!