I'm currently programming an MCTS AI for a game and I want to optimize the CPU bottlenecks. One method takes about 20% of all processing and returns to what team a piece/base on a position on a 2D String belongs. Bases are formatted as "b:000" where 000 is the teamId. Pieces are formatted as "p:000_1" where 000 is the teamId. All I want to do is get the 000 from the Id String as efficient as possible.
Currently my Code is the following:
public static int getOccupantTeam(String[][] grid, int[] pos, StringBuilder sb) {
sb = sb.delete(0, sb.length()).append(grid[pos[0]][pos[1]]);
int indexUnderscore = sb.indexOf("_");
return Integer.parseInt(sb.substring(sb.indexOf(":")+1, indexUnderscore == -1 ? sb.length() : indexUnderscore));
}
The StringBuilder is to reduce the amount of created Objects as I can create it once and use it as often as I want. Is there any way to make my code more efficient?
As a comment already says, you’re better off fixing the overall design. Use dedicated objects instead of formatted strings.
But if you want to keep the logic:
What’s striking is the entirely pointless use of a
StringBuilderhere. You’re emptying the builder at the beginning (viasb.delete(0, sb.length())), followed by copying a single string into it, just to perform operations on theStringBuilderwhich you could do on the originalStringin the first place.Besides that, since the location of the underscore is expected to be after the colon, you can search for the colon first and only search for the underscore after that position.
You can, of course, remove the obsolete
StringBuilderparameter now.If you are using Java 9 or newer, you can omit the
substringoperation:See
Integer.parseInt(CharSequence s, int beginIndex, int endIndex, int radix)