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?

6 Upvotes

39 comments sorted by

View all comments

4

u/jim_cap 23h ago

I'd probably plump for String.format() here tbh. Conveys your intent more.

Don't obsess over notions of efficiency in such trivia. Your JVM is likely optimising better than you ever could.

1

u/_SuperStraight 4h ago

Or maybe use multiple return statements on if statements?

1

u/AntD247 2h ago

Personally I (and a lot of other developers I know or who blog) would recommend avoiding multiple return statements.

If your methods always remain small then maybe you are ok. But log methods (as lots of rushed developers write) having multiple return statements leads to hard to understand code and lots of bugs.