Search code examples
programming-languages

Why are dynamically typed languages slow?


What makes it hard to speed up dynamically typed languages when compared to statically typed languages . In other words what is inherent property of statically typed languages that make them easy to optimize for speed of execution ?


Solution

  • When accessing attributes / methods in statically-typed languages, lookups can usually be reduced to a static function address. Even in the case of virtual methods, which are slower, the lookup is just reading an offset from a vtable.

    In dynamic languages, names are based on strings. Want to look up foo.bar? Find foo in the local variable hash table, then find bar in foo's hash table. In some dynamic languages, like Python and Ruby, there may be additional lookups/method calls to implement dynamically generated attributes.

    All of these lookups are very hard to make fast. Python has one of the most well-tuned hash table implementations in the world, and JavaScript has had millions of dollars of research money poured into making it fast. These tactics work -- compare Chrome's JavaScript with IE 5 to see just how much -- but they are much, much more difficult than just statically generating function calls.


    I should mention that how "dynamic" a language is can vary. Python has several different ways to interact with variable lookups, which is nice in some circumstances, but makes optimization very hard. Other dynamic languages, such as Common Lisp and Smalltalk, can compete evenly with static languages in many use cases because dynamic lookups/modifications are more controlled.