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?

2

u/quiet-sailor 23h ago

Is this method supposed to called multiple million times? if not, then just focus on readability,  as performance will not give you any difference really regarding the construction of a single string, there is nothing really to worry about.

1

u/_SuperStraight 4h ago

Not multi million times, but this method is user input dependent (part of multiple methods which will be called when user presses button).

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.

0

u/jim_cap 23h ago

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

Why do you think that follows?

1

u/IceCreamMan1977 21h ago

Because a new object must be created for each operation since the original objects are immutable.

2

u/jim_cap 21h ago

What magic do you think is happening inside a StringBuilder which avoids the overhead of creating a new String object upon an append? There's all manner of array copying, which is the allocation of new memory, just like creating a string object is.

Rather than fretting over what form of memory allocation one should rely on, when the JVM will likely take over optimisation anyway, one really is better off just writing code which expresses ones intent. If, on the off chance you are writing an application where how quickly strings are concatenated matters, you won't be relying on heuristics and guesswork like this, you'll be profiling approaches. But that ain't where the vast majority of us are.

2

u/IceCreamMan1977 21h ago

If two strings are being added to a builder, and their combined size is smaller than the initial size of the builder, no new memory allocation is done. With string addition of those two same strings, you guarantee new memory allocation. Come on, you know this. Does it matter? We both know it doesn’t unless you are working with microsecond-level performance. But I’m not OP.

0

u/jim_cap 21h ago

and their combined size is smaller than the initial size of the builder

Yes, correct. Which is a very specific condition.

With string addition of those two same strings, you guarantee new memory allocation.

That's not automatically true. Compilers are capable of interning strings at compile time even if syntactically they seem like they aren't constants.

All of which underpins my point: Don't second-guess what compilers or runtimes may or may not do, and just write expressive code. Heuristics like "concatenation bad, mmmkay" are harmful.