In Python, why is code running in a function faster than running in the global?

Source: Internet
Author: User
using Dis.dis to view functions, local variables are load_fast, faster than Load_global

============
Guess, when executing inside a function, the dictionary used to query the variable is smaller than the global case, so it is faster, or for another reason, a dictionary of variables may be used inside the function, which may have better locality in memory arrangement and can be faster.

>>> def do_test ():     ... A = 1     ... b = ' abc '     ... c = [] ...     Print locals () ... >>> do_test () {' A ': 1, ' C ': [], ' B ': ' abc '}>>> >>> a = 1>>> b = ' abc ' >>> C = []>>> Print locals () {' A ': 1, ' do_test ': <function do_test at 0x7fab08be8410> ' C ': [], ' B ' : ' abc ', ' __builtins__ ': <module ' __builtin__ ' (built-in);, ' __package__ ': None, ' __name__ ': ' __main__ ', ' __doc__ ' : None}

In addition, about Dict occupies memory, and the number of nodes related

>>> a = {}>>> for idx in range: ...     Print idx, sys.getsizeof (a)     ... A[IDX] = idx ... 0 2801 2802 2803 2804 2805 2806 10487 10488 10489 104810 104811 104812 104813 104814 104815 104816 104817 104818 104819 10 4820 104821 104822 335223 335224 335225 335226 335227 335228 335229 335230 335231 335232 335233 335234 335235 335236 33523 7 335238 335239 335240 335241 335242 335243 335244 335245 335246 335247 335248 335249 3352
  • 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.