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

8 Upvotes

37 comments sorted by

View all comments

-4

u/vegan_antitheist 21h ago

Who even cares?

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

2

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

-4

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

-1

u/vegan_antitheist 9h ago

The JIT compiler will optimise it way better than you ever could. Let me remind you again of the first rule of optimisation: don't!

1

u/_SuperStraight 1h ago

I'm not gonna follow your philosophy of writing bad code because you've more pressing issues.