I have a loop like:
String tmp;
for(int x = 0; x < 1000000; x++) {
// use temp
temp = ""; // reset
}
This string is holding at most 10 characters.
What would be the most effecient way of creating a variable for this use case?
Should I use a fixed size array? Or a stringbuffer instead?
I don’t want to create 1million variables when I don’t have to, and it matters for this method (performance).
Edit
I simplified my scenerio, I actually need this variable to be at the class level scope as there are some events that take place i.e. it can’t be declared within the loop.
Why not simply declaretempinside the loop like so:You even get a very (very, very) slight performance increase because you don’t have to waste time resetting the value of
tempto"".With regards to your update, It still depends on what you do with
tempbut a StringBuffer would probably be the easiest to use. And especially if you need to concatenate together a Sting, it would be quite fast.