“f-string vs string.join 的性能”

huangapple go评论58阅读模式
英文:

Performance of f-string vs string.join

问题

The 2 equivalent in time complexity?

result_1 = f'{one}{two}{three}'
result_2 = ''.join([one, two, three])

I know that join works in linear time. But is the same true also for f-strings?
With f-strings, the number of strings being concatenated is always a constant, so I guess one could say it's constant time complexity, but I was more curious to know how the concatenation is implemented and how it would fare with a large number of strings.

英文:
one = 'one'
two = 'two'
three = 'three'

Are the 2 equivalent in time complexity?


result_1 = f'{one}{two}{three}'
result_2 = ''.join([one, two, three])

I know that join works in linear time. But is the same true also for f-strings?
With f-strings, the number of strings being concatenated is always a constant, so I guess one could say it's constant time complexity, but I was more curious to know how the concatenation is implemented and how it would fare with a large number of strings.

答案1

得分: 1

以下是已翻译的内容:

这两种方法的性能可能会在不同版本的Python中有所不同,也可能取决于您的硬件。

在macOS 13.4上的Python 3.11.3(3 GHz 10核Intel Xeon W处理器)中,f-string的实现比str.join()更快。

from timeit import timeit

ONE = 'one'
TWO = 'two'
THREE = 'three'

def func1(one, two, three):
    return f'{one}{two}{three}'

def func2(one, two, three):
    return ''.join([one, two, three])

for func in func1, func2:
    print(func.__name__, timeit(lambda: func(ONE, TWO, THREE), number=2_000_000))

输出:

func1 0.2694316829999934
func2 0.33222394099993835

注意:

这个结果部分原因是func2必须构建一个列表。可以通过重写它来消除这个问题:

def func2(*args):
    return ''.join(args)

这个重写的性能由timeit报告为:

func2 0.30138257099997645
英文:

The performance of these two approaches may vary between releases of Python and could also depend on your hardware.

In Python 3.11.3 on macOS 13.4 (3 GHz 10-Core Intel Xeon W) the f-string implementation is faster than str.join()

from timeit import timeit

ONE = 'one'
TWO = 'two'
THREE = 'three'

def func1(one, two, three):
    return f'{one}{two}{three}'

def func2(one, two, three):
    return ''.join([one,two,three])

for func in func1, func2:
    print(func.__name__, timeit(lambda: func(ONE, TWO, THREE), number=2_000_000))

Output:

func1 0.2694316829999934
func2 0.33222394099993835

Note:

This result will be due in part to the fact that func2 has to construct a list. This can be eliminated by re-writing it as:

def func2(*args):
    return ''.join(args)

...which timeit reports as:

func2 0.30138257099997645

huangapple
  • 本文由 发表于 2023年5月21日 14:43:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76298624.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定