Skip to content

v3 generator: optimize hasdoc function to avoid full string scan #5321

@wucm667

Description

@wucm667

Is your feature request related to a problem? Please describe.

The hasdoc function in v3/internal/generator/render/doc.go uses strings.ContainsFunc to check if a comment group contains any non-whitespace character:

func hasdoc(group *ast.CommentGroup) bool {
    if group == nil {
        return false
    }
    // TODO: this is horrible, make it more efficient?
    return strings.ContainsFunc(group.Text(), func(r rune) bool { return !unicode.IsSpace(r) })
}

For large files with extensive documentation comments, this scans the entire comment text byte-by-byte just to determine if it contains any content beyond whitespace. The TODO comment in the source already acknowledges this inefficiency.

Describe the solution you would like

Replace the full-string scan with an early-return approach:

func hasdoc(group *ast.CommentGroup) bool {
    if group == nil {
        return false
    }
    for _, c := range group.List {
        text := strings.TrimSpace(c.Text)
        if len(text) > 0 {
            return true
        }
    }
    return false
}

This iterates over individual comment entries and returns true as soon as it finds any non-empty comment, avoiding scanning the full concatenated text.

Alternatively, use strings.IndexFunc which also short-circuits on the first match:

return strings.IndexFunc(group.Text(), func(r rune) bool { return !unicode.IsSpace(r) }) != -1

Describe alternatives you have considered

  • Keep the current implementation (acceptable for small projects, but suboptimal for large codebases with extensive documentation)
  • Cache the result if hasdoc is called multiple times on the same comment group

Additional context

This function is registered as a template function in v3/internal/generator/render/functions.go and is used during Go-to-TypeScript binding generation. For projects with large interfaces or many documented methods, this function may be called repeatedly during code generation.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions