JavaScript and Python – How Type Checking Works in Dynamic Language Interpreters

compilerjavascriptpython

In dynamic languages, such as JavaScript or Python, the type of a variable is determined at runtime. This is one reason why they are slower than typed languages such as Java.

How is type checking performed? What is the essential reason this process is slow?

Best Answer

There's confusion in the question.

There's an assumption that type checking is slow, which isn't necessarily the case.

The question also seems to confuse the process of type dispatch with type checking, and they are two different things. One is a process that's done at run time, the other a process at compilation time. I suspect the question is really asking about type dispatch.

It is type dispatch that can introduce overhead at runtime, because the computation spends time with instructions that decide, dynamically, what action to take, based on the types of values it sees at run time. e.g. in a dynamic language, if I apply "+" on two things, I might mean numeric addition, or string concatenation, so I need to spend time looking at what's at hand to decide what to do. There are evaluation strategies that can reduce the cost of dynamic dispatch. (e.g. tracing JITs)

With regards to doing type-checking in JavaScript, see: http://www.cs.brown.edu/~sk/Publications/Papers/Published/gsk-flow-typing-theory/. For a more general overview of how type checkers work, a standard programming language textbook will cover the algorithms. For example, http://www.cs.brown.edu/~sk/Publications/Books/ProgLangs/