Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance comparison Static Typing Python 3.6+ vs Cython

Recently Python 3.6 added static typing as a way to enforce certain types. This same functionality I used to get it from Cython, obtaining highly optimized functions when compared to vanilla Python.

My question then is: Will we also get substantial a performance increase when using the new Python static typing? pros/cons of each approach?

like image 520
ibarrond Avatar asked Aug 08 '18 09:08

ibarrond


People also ask

Does static typing make Python faster?

However, for performance critical code, it is often helpful to add static type declarations, as they will allow Cython to step out of the dynamic nature of the Python code and generate simpler and faster C code - sometimes faster by orders of magnitude.

Does Cython use type hints?

Recent Cython will use type hints, although it's more limited and buggy than the "traditional" ways., and probably doesn't include np.

Does Python support static typing?

Python will always remain a dynamically typed language. However, PEP 484 introduced type hints, which make it possible to also do static type checking of Python code. Unlike how types work in most other statically typed languages, type hints by themselves don't cause Python to enforce types.


2 Answers

Static typing in Python doesn't make it a compiled programing language. Therefore, performance-wise, you should always get better performance from Cython (Compiled should always beat Interpreted).

The main purpose of Python's newly added static typing is to perform type checking in a seamless way, bys sacrificing some of Python's philosophy on the way.

In short: Cython for speed, Python3.6 for interpreted/more pythonic approach.

like image 87
cerdipotamia Avatar answered Sep 22 '22 12:09

cerdipotamia


There is no static typing in any existing version of CPython, 3.7 or earlier.

The support for optional type annotations in CPython 3.6 (backported to 3.5 as well) helps the external tools such as static code analysers to verify that types are used consistently in a program.

Type hints have no impact on bytecode compilation or execution.

From CPython 3.6 What's new:

In contrast to variable declarations in statically typed languages, the goal of annotation syntax is to provide an easy way to specify structured type metadata for third party tools and libraries via the abstract syntax tree and the annotations attribute.

Note that however type hinting syntax can be used in Cython to define C types (Type Declaration Syntax).

like image 36
Oleh Rybalchenko Avatar answered Sep 24 '22 12:09

Oleh Rybalchenko