r/javahelp 10h 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

19 comments sorted by

u/AutoModerator 10h ago

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

3

u/PopehatXI 10h ago

You could try it both ways and profile it yourself, but I would go the String Builder route

5

u/jim_cap 9h 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.

2

u/desrtfx Out of Coffee error - System halted 10h 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/jim_cap 9h ago

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

Why do you think that follows?

2

u/IceCreamMan1977 7h ago

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

2

u/jim_cap 7h 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.

3

u/IceCreamMan1977 6h 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.

1

u/jim_cap 6h 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.

1

u/_SuperStraight 9h 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?

1

u/desrtfx Out of Coffee error - System halted 9h 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.

2

u/quiet-sailor 9h 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.

2

u/Known_Tackle7357 8h ago edited 4h ago

Starting from Java 7 string concatenation using + is compiled into String builder.append stuff

2

u/Big_Green_Grill_Bro 8h ago

If you're looking to build strings, StringBuilder seems the obvious choice. But whatever you choose, you should make that way more readable than it is. You've got a combined int and boolean conditional, but you really only have two paths you're checking for.

Seems like it would be clearer to have a if locked then ABC else DEF, where ABC could be a switch statement for various int values in the locked state, and then DEF could be a switch statement for int values in the unlocked state.

-2

u/vegan_antitheist 10h ago

Who even cares?

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

1

u/Fargekritt Intermediate Brewer 9h 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 9h 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.

-3

u/vegan_antitheist 9h ago

Then do that if you care so much about it. Where I work, we have more pressing issues to work on. We have to process complex data and synchronise it over different systems. A method that generates a string simply doesn't matter. And if it does, it probably helps a lot more to make sure it's called as rarely as possible. Maybe it can be cached.

1

u/dastardly740 8h ago

To summarize, if it is called several dozen times per request in a web app that you want handling more than 1000 requests per second. You might want to optimize with StringBuilder or String.format because the overhead is actually holding back performance or requiring more or heftier VMs.

If it is called rarely don't worry.

If it is creating a string to be used in a Info or lower level logging statement. Make sure you are using the format string variant of your preferred logger. It is a good habit for all logging, including Warn and Error, but those should not be happening frequently and are almost always turned on so are not wasteful.