Saturday, March 9, 2024

Java String Builder

String concatenation

  public String createReservationJsonResponse(Reservation reservation) 

    {

        String jsonResponse = "{"

                            + "\"ticketReservationNumber\":\"" + reservation.getTicketReservationNumber() + "\","

                            + "\"origin\":\"" + reservation.getOrigin() + "\","

                            + "\"destination\":\"" + reservation.getDestination() + "\","

                            + "\"date\":\"" + reservation.getDate() + "\","

                            + "\"seats\":" + Arrays.toString(reservation.getSeats()) + ","

                            + "\"numPassengers\":\"" + reservation.getNumPassengers() + "\","

                            + "\"estimationTripDuration\":\"" + reservation.getEstimationTripDuration() + "\""

                            + "}";


        return jsonResponse;

    }

StringBuilder

Tsing `StringBuilder` would be a more memory-efficient approach to constructing a JSON string, especially when dealing with concatenation of multiple strings. The `StringBuilder` class in Java is mutable and provides better performance for string concatenation operations compared to using the `+` operator or concatenating directly.


Here's how you could rewrite your method using `StringBuilder`:


public String createReservationJsonResponse(Reservation reservation) {

    StringBuilder jsonBuilder = new StringBuilder();

    

    jsonBuilder.append("{")

               .append("\"ticketReservationNumber\":\"").append(reservation.getTicketReservationNumber()).append("\",")

               .append("\"origin\":\"").append(reservation.getOrigin()).append("\",")

               .append("\"destination\":\"").append(reservation.getDestination()).append("\",")

               .append("\"date\":\"").append(reservation.getDate()).append("\",")

               .append("\"seats\":").append(Arrays.toString(reservation.getSeats())).append(",")

               .append("\"numPassengers\":\"").append(reservation.getNumPassengers()).append("\",")

               .append("\"estimationTripDuration\":\"").append(reservation.getEstimationTripDuration()).append("\"")

               .append("}");


    return jsonBuilder.toString();

}


This approach eliminates the creation of unnecessary intermediate `String` objects and is more memory-efficient. The `StringBuilder` instance is modified in place, and the final JSON string is obtained using the `toString()` method. It's a good practice, especially when dealing with dynamic string concatenation.

No comments:

Post a Comment

LeetCode C++ Cheat Sheet June

🎯 Core Patterns & Representative Questions 1. Arrays & Hashing Two Sum – hash map → O(n) Contains Duplicate , Product of A...