Speed up Katalon String operations

@em817m

Do you know programming terms: an object is mutable or immutable?

java.lang.String class is immutable. You are concatenating 2 strings with the + operator to produce a new String object. Your code will repeat instantiating a new String object and de-referencing the previous String object for 235K times. The String objects will consume much memory space, creating objects consumes CPU power. It is a bad practice repeating String concatenation using + operator.

There is a Java Class java.lang.StringBuilder, which is mutable. It is designed to perform string concatenation efficiently. Have a look at some article, for example;

The following sample shows how to use StringBuilder.

List<String> searchList = ["aaa", "bbb", "ccc"]

int searchListSize = searchList.size()
StringBuilder buf = new StringBuilder()
for (int i= 0; i < searchListSize; i++) {
	if (buf.size() > 0) {
		buf.append('\n')
	}
	buf.append(searchList[i])
}

println ">>>" + buf.toString() + "<<<"

Output:

>>>aaa
bbb
ccc<<<

You can swap the searchList to have 235K lines. StringBuilder would work in seconds.

1 Like