Skip to content

strings: genSplit improvement #18973

Description

@dongweigogo

#go1.7, linux, amd64

The genSplit function used by Split, SplitAfter and SplitAfterN is simplified in the IF statement of sep length, maybe for code expression. However it results in extra conditional executions in either case of len(sep)==1 or len(sep)>1

if s[i] == c && (len(sep) == 1 || s[i:i+len(sep)] == sep) {
...
}

Just seperating that into two parts according to sep length gains ~15% improvement in performace (15% time reduction) in either case of len(sep)==1 or len(sep)>1.

func genSplit(s, sep string, sepSave, n int) []string {

if n == 0 {
    return nil
}
if sep == "" {
    return explode(s, n)
}
if n < 0 {
    n = strings.Count(s, sep) + 1
}
c := sep[0]
start := 0
a := make([]string, n)
na := 0
if len(sep)==1 {
    for i := 0; i < len(s) && na+1 < n; i++ {
        if s[i] == c {
            a[na] = s[start : i+sepSave]
                na++
                start = i + 1
            }
        }
} else {
    for i := 0; i+len(sep) <= len(s) && na+1 < n; i++ {
        if s[i] == c && s[i:i+len(sep)] == sep {
            a[na] = s[start : i+sepSave]
            na++
            start = i + len(sep)
            i += len(sep) - 1
        }
    }
}
a[na] = s[start:]
return a[0 : na+1]

}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions