Skip to content

Commit

Permalink
[MNG-7899] Various memory usage improvements
Browse files Browse the repository at this point in the history
Merging the getStatus() method to optimize :

- Use the main StringBuilder to append string instead of using a
separate one
- Use the StringBuilder.append() with index to avoid String.substring(),
less temporary strings
- Reuse the FileSizeFormat object in the while loop avoiding multiple
temporary instances creation
  • Loading branch information
sebastien-doyon committed Sep 27, 2023
1 parent 14d1606 commit 607b420
Showing 1 changed file with 23 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,34 @@ public synchronized void transferProgressed(TransferEvent event) throws Transfer
buffer.append("Progress (").append(transfers.size()).append("): ");

synchronized (transfers) {
FileSizeFormat format = new FileSizeFormat(Locale.ENGLISH);

Iterator<Map.Entry<TransferResource, Long>> entries =
transfers.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<TransferResource, Long> entry = entries.next();
long total = entry.getKey().getContentLength();
Long complete = entry.getValue();
buffer.append(getStatus(entry.getKey().getResourceName(), complete, total));

String resourceName = entry.getKey().getResourceName();

if (printResourceNames) {
int idx = resourceName.lastIndexOf('/');

if (idx < 0) {
buffer.append(resourceName);
} else {
buffer.append(resourceName, idx + 1, resourceName.length());
}
buffer.append(" (");
}

buffer.append(format.formatProgress(complete, total));

if (printResourceNames) {
buffer.append(")");
}

if (entries.hasNext()) {
buffer.append(" | ");
}
Expand All @@ -89,25 +110,6 @@ public synchronized void transferProgressed(TransferEvent event) throws Transfer
out.flush();
}

private String getStatus(String resourceName, long complete, long total) {
FileSizeFormat format = new FileSizeFormat(Locale.ENGLISH);
StringBuilder status = new StringBuilder();

if (printResourceNames) {
int idx = resourceName.lastIndexOf('/');
status.append(idx < 0 ? resourceName : resourceName.substring(idx + 1));
status.append(" (");
}

status.append(format.formatProgress(complete, total));

if (printResourceNames) {
status.append(")");
}

return status.toString();
}

private void pad(StringBuilder buffer, int spaces) {
String block = " ";
while (spaces > 0) {
Expand Down Expand Up @@ -135,7 +137,7 @@ public synchronized void transferFailed(TransferEvent event) {

private void overridePreviousTransfer(TransferEvent event) {
if (lastLength > 0) {
StringBuilder buffer = new StringBuilder(128);
StringBuilder buffer = new StringBuilder(lastLength + 1);
pad(buffer, lastLength);
buffer.append('\r');
out.print(buffer);
Expand Down

0 comments on commit 607b420

Please sign in to comment.