Why is Python faster than C when concatenating two strings?

前端 未结 2 1946
旧时难觅i
旧时难觅i 2021-02-07 12:11

Currently I want to compare the speed of Python and C when they\'re used to do string stuff. I think C should give better performance than Python will; however, I got a total co

2条回答
  •  执念已碎
    2021-02-07 12:22

    I believe the reason for this is that Python strings are not null-terminated.

    in Python the string length is stored alongside the string, allowing it to skip the implicit strlen() used by strcat() when concatenating strings.

    Adding in the fact that string concatenation is implemented directly in C for Python is probably the cause.

    Edit: well, now that I actually look at the C code and see that it uses static buffers, I'm mystified as well, as I don't see how Python could avoid dynamic allocations which should be much slower...

提交回复
热议问题