user801116
user801116

Reputation:

What is the ideal way to append strings in groovy?

I need to create a string from a array of map in groovy.

Required string = ^(123|456|789)

At present I am doing something like below, will this cause performance issue in production box or should I use StringBuffer java class?

def getProjectList(def caseResult) {
    def projectList = ""
    caseResult.each { projno ->
        if (projectList.length() == 0) {
            projectList = "^(${projno.project_no}|"
        } else {
            if (projectList.indexOf(projno.project_no) == -1)
                projectList+="${projno.project_no}|"
        }
    }
    projectList = projectList.substring(0, projectList.length() - 1)
    projectList += ')'
    return projectList
}

Upvotes: 1

Views: 933

Answers (2)

tim_yates
tim_yates

Reputation: 171074

I'd go for ease of reading...

def getProjectList(def caseResult) {
    "^(${caseResult.project_no.join('|')})"
}

Actually, you just want the unique ones don't you?

def getProjectList(def caseResult) {
    "^(${caseResult.project_no.unique().join('|')})"
}

Upvotes: 2

Eel Lee
Eel Lee

Reputation: 3543

I need to create a string from a array of map in groovy.

It would be extremely useful to define parameter type then. The return type too.

will this cause performance issue in production box

Well, define performance issue first. Have you measured anything to think your code has any performance issues? If not, it looks like a typical "premature optimization"

should I use StringBuffer java class

If you worry about performance, then you should rather use StringBuilder, as StringBuffer is thread-safe, taking a little performance hit.

If your code suffers from anything, it's rather readability than performance. And I recommend you this StackExchange site, dedicated to such questions - https://codereview.stackexchange.com/ - give it a try!

Upvotes: 0

Related Questions