Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it less computationally intensive to use 7.0 or float(7) in Python?

Tags:

python

types

I'm curious which form is more efficient, is correct style, etc. I feel like the ".0" approach is much quicker; I'm not sure why the "float" approach is equally appreciated (if it is).

like image 700
Piper Avatar asked Jul 13 '12 18:07

Piper


2 Answers

Using float(7) adds some unnecessary overhead—Python has to find the float function in globals() and call it. Using 7.0 does all the necessary conversions at compile-time instead of run-time. You can see this using the Python bytecode disassembler.

>>> import dis
>>> def f(): return 7.0
... 
>>> def g(): return float(7)
... 
>>> dis.dis(f)
  1           0 LOAD_CONST               1 (7.0)
              3 RETURN_VALUE        
>>> dis.dis(g)
  1           0 LOAD_GLOBAL              0 (float)
              3 LOAD_CONST               1 (7)
              6 CALL_FUNCTION            1
              9 RETURN_VALUE        
like image 182
Michael Hoffman Avatar answered Oct 09 '22 09:10

Michael Hoffman


use the 7.0 approach, the float(7) approach is used to transform integer or string types to floats so it's a different use, for example:

a = 7
b = "7"
print float(a)
7.0
print float(b)
7.0
like image 35
Hassek Avatar answered Oct 09 '22 07:10

Hassek