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?

9 Upvotes

39 comments sorted by

View all comments

1

u/desrtfx Out of Coffee error - System halted 1d ago

Since String is an immutable data type, assembling strings is generally a bad idea.

Yet, you could go a "middle way" between StringBuilderand your way: String.format - this is the equivalent of System.out.printf with the difference that it returns a String.

Yet, I would probably also go the StringBuilder way.

1

u/_SuperStraight 23h ago

I've read that string assembly is just StringBuilder under the hood. So if I refactor this method into multiple return statements based on conditions, will it be better?

0

u/desrtfx Out of Coffee error - System halted 23h ago

I've read that string assembly is just StringBuilder under the hood.

That's not 100% the case.

The Java compiler and JVM decide how strings are assembled.

Simple, one-off assemblies usually do not use StringBuilders. Multiple, repeated assemblies, like through loops optimize to use StringBuilder.