Speed up Katalon String operations

I have a situation where I have to build a string that is used as input to a UI Text Area. There are 235K lines of data that are read from a flat file, put into a list and then read out, one-by-one and appended with a new line character and then put into a string.

The reading from a flat file and creating the list is reasonable within Katalon. But it’s taking 25 minutes to create the string. The entire Test Case takes 31 minutes to run so I’ve been asked to look into this issue.

My code is here:

//searchList holds the 235K lines of raw input data from the flat file
int searchListSize = searchList.size()
String mispSearchString = ''
for (int row = 0; row < searchListSize; row++) {
	if ((row + 1) == searchListSize) {
		mispSearchString = (mispSearchString + searchList.get(row))
	} else {
		mispSearchString = ((mispSearchString + searchList.get(row)) + '\\n')
	}
}

Everything works, it’s just taking too long.

Doesn’t the flat file already include newline chars? If it does…

Don’t read it into a list, just read the file into a string:

String readFileIntoString(String filepath) {
  File file = new File(filepath)
  return file.text
}

Hopefully, that will retain the existing \n chars

1 Like

@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.

kazurayam,
Thank you for your suggestion & example. Your code brought the load time down to 1 second from 25 minutes.