jonschlinkert / kind-of

Get the native JavaScript type of a value, fast. Used by superstruct, micromatch and many others!
https://github.com/jonschlnkert
MIT License
347 stars 38 forks source link

Question #11

Closed macsmac closed 7 years ago

macsmac commented 7 years ago

Why would you do a lot of conditions instead of...

function getType(query) {
  return query.constructor ? 
    String(query.constructor.name).toLowerCase() || typeof query 
    : typeof query;
}

It does pretty much the same

getType(new UInt8Array()); // "uint8array"
getType(new WeakMap()); // "weakmap"

Isn't it faster?

macsmac commented 7 years ago

Actually this code will be much faster:

function type(query) {
    if (query) {
        return query.constructor.name.toLowerCase();
    } else if (query === undefined) {
        return "undefined";
    } else if (query === null) {
        return "null";
    }
}

And much faster then kind-of. To confirm this I wrote benchmark:

const Benchmark = require("benchmark");
const suite = new Benchmark.Suite();

const kind = require("kind-of");

function type(query) {
    if (query) {
        return query.constructor.name.toLowerCase();
    } else if (query === undefined) {
        return "undefined";
    } else if (query === null) {
        return "null";
    }
}

suite
    .add("a lot of conditions", function() {
        kind(new WeakMap());
    })
    .add("constructor name", function() {
        type(new WeakMap());
    })
    .on("cycle", function(event) {
        console.log(String(event.target));
    })
    .on("complete", function() {
        console.log("Fastest is " + this.filter("fastest").map("name"));
    })
    .run({
        async: true
    });

Logs:

a lot of conditions x 812,575 ops/sec +2.92% (76 runs sampled)
constructor name x 2,168,337 ops/sec +1.39% (77 runs sampled)
Fastest is constructor name
jonschlinkert commented 7 years ago

Isn't it faster?

No