From 17b6761323f42a30b68aba72bdd62ffead1ffc43 Mon Sep 17 00:00:00 2001 From: Julien Kronegg Date: Wed, 29 Mar 2023 14:22:34 +0200 Subject: [PATCH] Improved padding performance Replaced `String` concatenations by `StringBuilder`. This code is 2.5 faster than the original one (using JMH Benchmark on padding left/right/center of an empty String with 50 "-"). --- .../markdowngenerator/util/StringUtil.java | 41 +++++++++++-------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/util/StringUtil.java b/Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/util/StringUtil.java index 89f2f60..0dc8249 100644 --- a/Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/util/StringUtil.java +++ b/Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/util/StringUtil.java @@ -26,36 +26,43 @@ public static String fillUpLeftAligned(String value, String fill, int length) { if (value.length() >= length) { return value; } - while (value.length() < length) { - value += fill; + StringBuilder valueBuilder = new StringBuilder(length); + valueBuilder.append(value); + while (valueBuilder.length() < length) { + valueBuilder.append(fill); } - return value; + return valueBuilder.toString(); } public static String fillUpRightAligned(String value, String fill, int length) { - if (value.length() >= length) { + int valueLength = value.length(); + if (valueLength >= length) { return value; } - while (value.length() < length) { - value = fill + value; + StringBuilder valueBuilder = new StringBuilder(length); + int fillLength = length - valueLength; + while (valueBuilder.length() < fillLength) { + valueBuilder.append(fill); } - return value; + valueBuilder.append(value); + return valueBuilder.toString(); } public static String fillUpCenterAligned(String value, String fill, int length) { - if (value.length() >= length) { + int valueLength = value.length(); + if (valueLength >= length) { return value; } - boolean left = true; - while (value.length() < length) { - if (left) { - value = fillUpLeftAligned(value, fill, value.length() + 1); - } else { - value = fillUpRightAligned(value, fill, value.length() + 1); - } - left = !left; + int fillLeftCount = (length - valueLength) / 2 / fill.length(); + StringBuilder valueBuilder = new StringBuilder(length); + for (int i=0; i