Alex Rivera | Logout

How exactly does Javascript instanceof work? Is it slow style?

Asked 2011-05-08T01:22:54.140
12

How does the performance of instanceof fair for "huge libraries"?

Does it travel up the prototype chain one by one, similar to this? :

//..
var _ = john.constructor;
while (true) {
    if (_ === Human) {
        return true;
    }
    _ = _.prototype.constructor
}
return false;
//..

Is instanceof relatively unperfomant then, compared to storing a unique interface id number in the property of every object.

Edit
Report

1 Answer

12

Yeah something like that. Here is the relevant part from the specification:

11.8.6 The instanceof operator

The production RelationalExpression: RelationalExpression instanceof ShiftExpression is evaluated as follows:

  1. Let lref be the result of evaluating RelationalExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating ShiftExpression.
  4. Let rval be GetValue(rref).
  5. If Type(rval) is not Object, throw a TypeError exception.
  6. If rval does not have a [[HasInstance]] internal method, throw a TypeError exception.
  7. Return the result of calling the [[HasInstance]] internal method of rval with argument lval.

where calling the [[HasInstance]] method is defined as

15.3.5.3 [[HasInstance]] (V)

Assume F is a Function object.

When the [[HasInstance]] internal method of F is called with value V, the following steps are taken:

  1. If V is not an object, return false.
  2. Let O be the result of calling the [[Get]] internal method of F with property name "prototype".
  3. If Type(O) is not Object, throw a TypeError exception.
  4. Repeat
    a. Let V be the value of the [[Prototype]] internal property of V.
    b. If V is null, return false.
    c. If
    answered 2011-05-08T01:35:03.440

Your Answer