Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

python - Is concatenating with "+" more efficient than separating with "," when using print?

I just noticed that if I use + for concatenation in the print() function and run the code in the shell the text appears more quickly. Whereas, when using ,, the text appears much slower as if with a "being typed" animation effect.

Is there a efficiency difference between these two?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Though I wouldn't suspect a large discrepancy between these, they are obviously slightly different.

A print call that concatenates literal strings might be joined by CPython's peephole optimizer before being printed thereby resulting in faster execution, this is probably what you're seeing. Besides that, with small strings, the fact that only one argument is passed and, as a result, sep isn't used is also a small benefit.

With larger strings, the need to create a large temporary string to hold their concatenation negates all speed differences achieved. (The fact that sep isn't used and only one argument is passed is trumped due to the size and their concatenation)

Using , in a print call will pass each string as an argument and separate it using the default sep. While this obviously requires a bit more work, it is constant work that, again, disappears when large strings are involved.

So, with small strings that actually get caught by the optimizer, concatenation is a bit faster:

%timeit print("a" + "b", file=f)
1000000 loops, best of 3: 1.76 μs per loop

%timeit print("a", "b", sep='', file=f)
100000 loops, best of 3: 2.48 μs per loop

Even when the optimizer can't join them:

a = "a"; b = "b"

%timeit print(a + b, file=f)
1000000 loops, best of 3: 2 μs per loop

%timeit print(a, b, sep='', file=f)
100000 loops, best of 3: 2.45 μs per loop

when the string sizes increase, this small difference is eclipsed:

s1, s2 = "s" * 100000, "s"*100000
%timeit print(s1 + s2, file=f)
1000 loops, best of 3: 374 μs per loop
%timeit print(s1, s2, sep='', file=f)
1000 loops, best of 3: 373 μs per loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...