by cheald · 13y ago · 0 comments
Dynamically-typed languages are often easier to program in, but require more copying (and memory allocation) as a result. Hash tables are heap-allocated and have to be garbage collected, but they're flexible - something you don't get with structs. Allocating and freeing memory has a cost, and that can add up quickly. Your primary line of optimization in most of these languages is "avoid the GC", which really boils down to "don't allocate more than you need to", which is sound advice in every language, scripting or otherwise.
I think the idea that GC is what slows down dynamic languages has to be the most prevalent misconception about language performance.
dynamic typing prevents type-based optimization
monkey patching prevents optimization
I think the most common complaint I hear about GC is not that it affects computational throughput, but that it affects _predictability_ of computational throughput. One maybe doesn't care in scientific computing, but game developers are always going on about how they can't use a GC language because a stall mid-frame will knock them over 16ms/frame or 33ms/frame, which for console certification is a project-killer.http://people.cs.umass.edu/~emery/pubs/gcvsmalloc.pdf
In a copy collector the GC time is proportional to the amount of live memory -- garbage is free. In FP-style programs (lots of short-lived allocations) GC can be essentially free.
The other main source of slowdown is to do with boxing and type checks. Accessing all data in a naive implementation of a dynamically typed language involves at least one type check and typically one pointer indirection to unbox the data. This can kill performance relative to the unboxed and unchecked equivalent. Consider, e.g., floating point operations -- they run in 1 cycle. If you add type check (2-3 cycles perhaps) and pointer indirection (10 cycles if it's in the cache) you can see how massive slowdowns easily arise.
Modern JS VMs will remove most of this cost. I doubt Python and Ruby do.
Basically, I would say it really depends on the interactions between the program and the language implementation.
In the python case, pypy removes this cost whenever it can. The less you use dynamic features like duck typing, the faster your code gets.
Heap allocations are expensive even in non-GC languages.
You can get away from that with a sufficiently smart JIT turning a stable access to a known object into little more than a vtable dispatch. That's close to what V8 does with hidden classes on full cache hits (object map — its "hidden class" — + object "array" property both cached).
point.x
will generate the assembly: cmp [ebx,<hidden class offset>],<cached hidden class>
jne <inline cache miss>
mov eax,[ebx, <cached x offset>]
(where ebx is the previously loaded `point`)