Skip to content
Advertisement

Code taking forever to excute when turned to string Java? [closed]

When I change the String m1 to a 2D int array it runs super fast but now it takes over an hour to just loop 10 pictures also each picture takes almost double the time the first one took . Is there a way where I can improve my code so it runs faster as I need to save all values as one String in the end ?

JavaScript

Advertisement

Answer

Your understanding of string performance may be the issue.

Strings are immuttable, so every change to a string makes a new String, it doesn’t alter the existing string.

JavaScript

doesn’t create one string. It creates a string for the red value, then creates a string that containts that in addition to a “:”, and then creates a string that contains that in addition to the green value, and then creates a string that contains that in addition to the …. (and so on)

So instead use a StringBuilder, which is like a buffer of RAM that holds String contents which can be manipulated without creating new Strings. When you want the String value for the buffer, call .toString() to create a new String.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement