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?
-
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 minimal reproducible example showing what you've done so far, along with your concrete performance requirements, would really help.– Jon SkeetCommented Dec 16, 2016 at 9: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...– GreenThorCommented Dec 16, 2016 at 10:23
Add a comment
|
1 Answer
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
-
1
-
@Kayaman thanks! is the best time i do a benchmark I will do next properly :)– cralfaroCommented Dec 16, 2016 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. Commented Dec 16, 2016 at 10:27