3
\$\begingroup\$

I need to call this function over a big dataset. I need it to be as efficient as possible but still be readable. Can I make it anymore efficient by using a different function for capitalize or blank check?

public static String nameFormat(String title, String firstname, String lastName) { if (StringUtils.isBlank(firstname) && StringUtils.isBlank(lastName)) { return "Unknown"; } StringBuilder fullNameSB = new StringBuilder(lastName.trim().toUpperCase()); fullNameSB.append(", "); fullNameSB.append(WordUtils.capitalizeFully(firstname.trim())); if (title != null) { fullNameSB.append(" "); // replace (mr.) with mr title = title.trim().replaceAll("\\.|\\)|\\(", ""); fullNameSB.append("("); fullNameSB.append(WordUtils.capitalize(title)); fullNameSB.append(")"); } //Remove any double spaces that might be in a multipart first or surname return fullNameSB.toString().replaceAll(" ", ""); } 
\$\endgroup\$
0

1 Answer 1

2
\$\begingroup\$

I assume WordUtils and StringUtils are Apache Commons? If so, it would be helpful for us for you to link to their online documentation/source.

The first thing to do when optimizing is to make sure you're optimizing the right thing. You might find ways to shave off a bit of running time in this method, but if this method is only responsible for 1% of the total running time then that's not very good use of your effort.

The thing that strikes me is all of the safety for weird conditions. I can pretty much guarantee you that your replaceAll calls are the slowest things. Maybe upstream code should be ensuring that the title is of the correct form to begin with, the strings are trimmed, and there are no double spaces.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.