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(", ");
    if (title != null) {
        fullNameSB.append(" ");
        // replace (mr.) with mr
        title = title.trim().replaceAll("\\.|\\)|\\(", "");
    //Remove any double spaces that might be in a multipart first or surname
    return fullNameSB.toString().replaceAll("  ", "");


1 Answer 1


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.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.