Why do monomorphic and polymorphic matter in JavaScript?

前端 未结 2 1243
梦如初夏
梦如初夏 2021-01-31 04:33

I\'ve been reading some articles on change detection, and all of them say that monomorphic functions are much faster than polymorphic. For example, here is a quote:

2条回答
  •  天涯浪人
    2021-01-31 05:30

    To my knowledge, monomorphism is a very uncommon term. I've personally never heard it used for coding. To figure out what monomorphism is, though, I think we can infer what it means by looking at what polymorphism is.

    Polymorphism: is the idea that many (poly-) different objects can be represented by the same type to the machine/runtime/interpreter. For instance, in C#, you may have as many classes as you want that implement ICloneable and any of them could be used in a copy constructor for a generic linked list (for example). Full un-tested class here as an example if you're interested

    Ok so what does monomorphic mean?

    Monomorphic to me means that the interpreter of the object handles the EXACT type that it is expecting, and no inheritance or modifications to the type expected is possible. In this context, with the duck typed javascript language, the VM says "this javascript object has these exact properties which are of these exact types and named exactly like they are". In C#, if we wanted to be monomorphic, then generic type restrictions would be impossible because T would have to be the same type all the time.

    This link provides a good guide as to why this matters to performance. To me this is can be summed up below.

    Javascript engines would like to avoid table lookups for properties, and instead to do object pointer offsets. With monomorphism, the object offsets for objects in a given line of code will always be the same and the VM has an easy time figuring out how to perform lookups with pointer addition rather than table lookups.

    In reality, the engines try to handle a small amount of different objects being passed to the same function but the VM will be fastest if the object always looks the same on the same line of code.

    Example for clarity

    The following example is valid javascript, but the argument o to function f1 is NOT monomorphic, because the VM needs to handle two differently shaped objects being passed in.

    function f1(o) {
      console.log(o.prop1)
      console.log(o.prop2)
    }
    
    // ...
    
    o1 = { prop1: 'prop1', prop2: 'prop2' }
    o2 = { prop1: 'prop1', prop2: 'prop2', prop3: 'prop3' }
    
    f1(o1)
    f1(o2)

    The point of the quote from the link that you provided is that AngularJS out of the box provides code which makes all of its javascript function arguments to be "monomorphic" because the objects passed into them happen to have the same structure every time they are called.

提交回复
热议问题