Python string Connection efficiency issues

Source: Internet
Author: User

The connection efficiency of strings has been mentioned in the discussion of Python efficiency, and most recommend using join instead of "+" for string connections

Everything in Python object string object is the C API stringobject.c see Python Source objects file can be found


1. "+". Using the plus sign to connect 2 strings calls the static function String_concat (register pystringobject *a, register pyobject * b), which in this function will open a block of memory that is the size of a+b and then A, b string Copy in, imagine, if it is n strings connected then will open up n-1 times memory, is more resource-intensive


2. For the use of the Join function "". The join ([A, b]) call to the String_join function calculates the length of the list one time to allocate a chunk of memory and then copy it, so the number of times that n strings are connected to open memory is 1 times.




So if there's only 2 connections, the difference is small, but there's a lot of data.


Add something (note) Python differs from the C language when creating variables

1. Integer, Python has a small integer buffer pool that has a range when defining an integer a=3. Then delete this integer using B=3 to find the address of A, B, and then use C = 1000023 to perform the above operation we found 2 number of addresses not the same small integer buffer pool


2. Python defines a string s = "Hello", g = "Hello" after, the address of S,g is the same, C language definition char a[5] = "Hello", char b[5] = "Hello", the string address of A and B is different, indicating that another memory is requested, PY The interned mechanism used by Thon first queries

Python string Connection efficiency issues

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.