What are some bad habits that make Python programs run slowly?

  Unlike other programming languages, Python is a strongly typed language, so when the interpreter encounters variables, comparison operations, data type conversions, and reference variables, it needs to check its data type, so the Python program runs slowly. Of course, the reason why the Python program runs slowly is not just that simple, maybe one of our bad habits will also slow down the Python program, let's take a look.

  1. Do not import the root module

  One thing we cannot avoid when using Python is importing modules, whether built-in or third-party. Sometimes, we may only need one or a few functions or objects in that module. In this case, we should try to import only the functions or objects we need, instead of importing the root module.

  2. Avoid dots/dotchains

  Using dot is very intuitive. Access properties or functions of objects in Python. Most of the time, no problem. However, if we can avoid using dots or even linking dots, performance will actually be better.

  3. Do not use + to concatenate strings

  Strings are immutable in Python. So when we use "+" to concatenate multiple strings into one long string, each substring is operated on individually.

  4. Do not use temporary variables for value exchange

  Many algorithms require the exchange of values ​​of two variables. In most other programming languages, this is usually done by introducing a temporary variable.

  5. Use If-Condition to short circuit

  Short-circuit evaluation exists in many programming languages, and so does Python. Basically, it refers to the behavior of certain boolean operators where the second argument is only executed or evaluated if the first argument is insufficient to determine the value of the entire expression.

  6. Don’t use a while loop if you can use a For loop

  Python uses a lot of C for performance, CPython. In terms of loop statements, a For-Loop in Python has relatively few steps, more of which run as C code than a while-Loop.

  So we should not use while loop when we can use For-Loop in Python. This is not only because For-Loop is more elegant in Python, but also because it performs better.

Guess you like

Origin blog.csdn.net/oldboyedu1/article/details/131229937