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

Source: Internet
Author: User
In Python, why is code running faster in a function than in a global one? Use dis. dis to view the function. The local variable is LOAD_FAST, which is faster than LOAD_GLOBAL.

================
Assume that the dictionary used to query variables is faster when the function is executed internally than the global one. Or another reason, the dictionary of variables may be used internally in the function, it may have better locality and speed in the memory arrangement.

>>> 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': 
 
  , 'c': [], 'b': 'abc', '__builtins__': 
  
   , '__package__': None, '__name__': '__main__', '__doc__': None}
  
 

In addition, dict memory usage is related to the number of nodes.

>>> a = {}>>> for idx in range(50):...     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 104820 104821 104822 335223 335224 335225 335226 335227 335228 335229 335230 335231 335232 335233 335234 335235 335236 335237 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.