Reputation: 5140
In my application I'm using constant suffix for a field value which gets updated every 2 seconds, something like: "some_value km/h" where km/h is a constant suffix. Currently I'm just doing simple concatenation of the value with the constant suffix declared as static final String
, but I know this way each 2 seconds I'm creating new String
. Is there a better way for doing it?
EDIT: Code example:
public static final String KM_SUFFIX = " km/h";
public void String getFormattedValue(int val) {
return val + KM_SUFFIX;
}
One more note: I'm using this on a mobile app and this constantly changing field is a part of a list item in a list which contains lots of items.
Upvotes: 2
Views: 408
Reputation: 22342
As other have said, this isn't going to be a performance problem. Strings are immutable, but they're also quick(well, short ones like these are, anyway)
That said, if you really, really don't want to concatenate the strings each time, you'll have to have two TextView
s to put them in. One would simply hold the static suffix value "km/h", and you could update the other with just the value.
The problem with this, of course, is that you'll have twice as many text fields for the OS to measure, lay out, and display. That probably won't be much of an issue, but it's still more work than creating/disposing of a string or two.
To sum up, the performance hit you get for either method will be negligible. As in, not noticeable. If you find you're having performance problems, profile it to find out where they are. This is a classic case of premature optimization.
Upvotes: 1
Reputation: 3718
you could make a Tempo class, with the unit and the some_value;
then you have your toSTring()- method, which returns you the string, you don't have to change the unit, you only have to change the some_value field.
Upvotes: 0
Reputation: 1467
Strings are immutable in Java. If you're changing the string every 2 seconds, you're making a new one every 2 seconds and there's no way around that.
Upvotes: 0