Format strings vs concatenation

前端 未结 7 671
天命终不由人
天命终不由人 2020-11-28 09:18

I see many people using format strings like this:

root = \"sample\"
output = \"output\"
path = \"{}/{}\".format(root, output)

Instead of si

7条回答
  •  没有蜡笔的小新
    2020-11-28 09:33

    I agree that the formatting is mostly used for readability, but since the release of f-strings in 3.6, the tables have turned in terms of performance. It is also my opinion that the f-strings are more readable/maintainable since 1) they can be read left-right like most regular text and 2) the spacing-related disadvantages of concatenation are avoided since the variables are in-string.

    Running this code:

    from timeit import timeit
    
    runs = 1000000
    
    
    def print_results(time, start_string):
        print(f'{start_string}\n'
              f'Total: {time:.4f}s\n'
              f'Avg: {(time/runs)*1000000000:.4f}ns\n')
    
    
    t1 = timeit('"%s, %s" % (greeting, loc)',
                setup='greeting="hello";loc="world"',
                number=runs)
    t2 = timeit('f"{greeting}, {loc}"',
                setup='greeting="hello";loc="world"',
                number=runs)
    t3 = timeit('greeting + ", " + loc',
                setup='greeting="hello";loc="world"',
                number=runs)
    t4 = timeit('"{}, {}".format(greeting, loc)',
                setup='greeting="hello";loc="world"',
                number=runs)
    
    print_results(t1, '% replacement')
    print_results(t2, 'f strings')
    print_results(t3, 'concatenation')
    print_results(t4, '.format method')
    

    yields this result on my machine:

    % replacement
    Total: 0.3044s
    Avg: 304.3638ns
    
    f strings
    Total: 0.0991s
    Avg: 99.0777ns
    
    concatenation
    Total: 0.1252s
    Avg: 125.2442ns
    
    .format method
    Total: 0.3483s
    Avg: 348.2690ns
    

    A similar answer to a different question is given on this answer.

提交回复
热议问题