I just want to set a placeholder in a String to a running number in a big loop. For convenience the placeholder is %d
. What is faster, using String's .format or .replace method?
Asked
Active
Viewed 121 times
-1

GreenThor
- 456
- 5
- 14
-
Have you tried both? What were your results? Is it possible to format the number to a fixed number of digits? (If so, creating a char array to reuse may well help...) Basically you haven't provided enough information here yet. A [mcve] showing what you've done so far, along with your concrete performance requirements, would really help. – Jon Skeet Dec 16 '16 at 09:59
-
@JonSkeet I was concentrating to much on coding and though just to throw this question into the room. I'm sorry I forgot about the guidelines, really need to think my questions through... – GreenThor Dec 16 '16 at 10:23
1 Answers
1
as I didn't know the response but I was curious about it I did a very simple test and add metrics and those are the results:
The code:
@Test
public void test(){
String original = "This is the phrase %d";
long init = System.currentTimeMillis();
for(int i = 0; i < 100000; i++){
System.out.println(String.format(original, i));
}
long end = System.currentTimeMillis();
long init1 = System.currentTimeMillis();
for(int i = 0; i < 100000; i++){
System.out.println(original.replace("%d", String.valueOf(i)));
}
long end2 = System.currentTimeMillis();
System.out.println("Method 1: " + (end-init));
System.out.println("Method 2: " + (end2-init1));
}
The results
Method 1: 1950 Method 2: 1361
So we can assume .replace is faster than String's format method

cralfaro
- 5,822
- 3
- 20
- 30
-
1Here's some reading http://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java – Kayaman Dec 16 '16 at 10:10
-
@Kayaman thanks! is the best time i do a benchmark I will do next properly :) – cralfaro Dec 16 '16 at 10:14
-
I suspect there are far quicker options as well, working out where the format string is, and creating an appropriate `char[]`, then just replacing the relevant characters each time. – Jon Skeet Dec 16 '16 at 10:27