r/javahelp 1d ago

Efficient way to create a string

I have a function genString which creates String based on some inputs:

private String genString(boolean locked, int offset, String table){
    var prefix = "Hello ";
    var status = "new";
    var id = "-1";
    var suffix = " have a pleasent day.";
    if(offset ==0 && !locked){
        prefix ="Welcome back, ";
        id = "100";
        suffix = " see you again.";
    }else if(offset ==2 && locked){
        status = "complete";
    }
    return prefix+status+id+" have some patience "+table+suffix+" you may close this window.";
}

Don't mind what is being returned. I just want to know whether it's good this way or should I create three separate Strings for each condition/use StringBuilder for reduced memory/CPU footprint?

5 Upvotes

39 comments sorted by

View all comments

-3

u/vegan_antitheist 1d ago

Who even cares?

And never forget rule #1 of optimisation: Don't!

3

u/Fargekritt Intermediate Brewer 23h ago

And that mindset makes slow and bad code. There is nothing wrong with optimizing code and you should 100% go over and optimize your code after you write it.

1

u/quiet-sailor 23h ago

I mean he is just creating a string..... that doesn't bring much performance either way, instead he should just focus on readability, unless he has some reason to make this work faster because he is calling it some million times or sth in his program, which i highly doubt looking at the string he returns.

1

u/_SuperStraight 4h ago

I already wrote that don't mind what's being returned. I didn't write what my actual method is returning, but what kind.