Skip to content

Replace str.format() with str.join() for faster string concatenation #305

@SaFE-APIOpt

Description

@SaFE-APIOpt

domain = "{}".format(domain[0])

Current code:

if len(domain) is 1 :
    domain = "{}".format(domain[0])
elif len(domain) is 2 :
    domain = "{}{}".format(domain[0], domain[1])
elif len(domain) is 3 and not "[" in domain[2]:
    domain = "{}{}".format(domain[0], domain[2])
else:
    domain = "{}{}".format(domain[0], domain[1])

Proposed replacement:

if len(domain) is 1:
    domain = ''.join([domain[0]])
elif len(domain) is 2:
    domain = ''.join([domain[0], domain[1]])
elif len(domain) is 3 and '[' not in domain[2]:
    domain = ''.join([domain[0], domain[2]])
else:
    domain = ''.join([domain[0], domain[1]])

str.join() is more efficient for string concatenation because it first calculates the total length of all strings, allocates memory once, and then performs the concatenation in a single pass. In contrast, str.format() needs to parse the format template and convert each argument before concatenation, which introduces extra overhead. Therefore, replacing str.format() with ''.join() improves both performance and clarity in this scenario.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions