Search code examples
javastringstring-pool

What memory (or performance) issues does the two approaches have?


Being a novice Java developer and having read about the String class and still somewhat confused about it's functionality. So, I decided to write a method to capitalize a user's name in the form, john changes to John using the code below:

1st Approach

   String firstUpper = username.substring(0, 1).toUpperCase();
   String restLower = username.substring(1).toLowerCase();
   return firstUpper.concat(restLower);
   

2nd Approach (method chaining)

   return username.substring(0,1).toUpperCase().concat(username.substring(1).toLowerCase());

Solution

  • No real implications in the performance or any memory inflation.

    In the first approach you are declaring two variables that point to the username string content and then make some changes to the string, creating two new strings after that you return the concatenation of those two new strings which result in a third new String.

    The second approach you are doing the same thing but with invisible variables (after you substring you always create a new String in the heap). The same thing about the concat operation. So in terms of the virtual machine and in the code produced they will to the same thing and have almost the same code generated (Where strings are create to new spaces in the memory).