lukeed / taskr

A fast, concurrency-focused task automation tool.
MIT License
2.53k stars 74 forks source link

Make stamp util be not ingored by v8 optimized compiler #226

Closed hzlmn closed 7 years ago

hzlmn commented 7 years ago

Made stamp not ingored by v8 optimized compiler.

TL;DR Just a weird shit, butarguments is ignored by v8 optimized compiler, if we use it incorrectly Basically functions with arguments usage become optimized only when

var mock = {
    log: function () {

    },

    error: function () {

    }
}

function stamp() {
    const args = [].slice.call(arguments);
    mock[this.method].apply(mock, (this.custom ? [this.custom].concat(args) : args));
}

function log() {
    stamp.apply({method: 'log', color: 'magenta'}, arguments);
    return this;
}

function error() {
    stamp.apply({method: 'error', color: 'red'}, arguments);
    return this;
}

function alert() {
    if (process.env.VERBOSE) {
        stamp.apply({
            color: 'yellow',
            method: 'log'
        }, arguments);
    }
    return this;
}

function loop() {
    for (var i = 0; i < 1e5; i++) {
        log('print', i)
    }
}

console.time('--nonopt--')
loop()
console.timeEnd('--nonopt--')

--nonopt--: 44.921ms

var mock = {
    log: function () {   
    },

    error: function () {

    }
}

var utils = {
    stamp: function () {
        var args = new Array(arguments.length)
        for (var i = 0; i < arguments.length; i++) {
            args[i] = arguments[i]
        }
        var param = this.custom ? [this.custom].concat(args) : args
        mock[this.method](param)
    },

    log: function () {
        this.stamp.apply({ method: 'log', color: 'magenta' }, arguments)
        return this
    },

    error: function () {
        this.stamp.apply({method: 'error', color: 'red'}, arguments);
        return this
    },

    alert: function () {
        if (process.env.VERBOSE) {
            this.stamp.apply({
                color: 'yellow',
                method: 'log'
            }, arguments);
        }

        return this
    }
}

function loop() {
    for (var i = 0; i < 1e5; i++) {
        utils.log('print', 'verbose')
    }
}

console.time('--opt--')
loop()
console.timeEnd('--opt--')

--opt--: 13.530ms

Intermediate representation with IR-Hydra

IR-Hydra is a tool that allow you to see 'optimization status' of v8 As you can see called stamp is ignored

2016-10-28 17 13 30

and here with fixed ver.

2016-10-28 17 13 46

ref: http://mrale.ph/blog/2015/11/02/crankshaft-vs-arguments-object.html

jorgebucaran commented 7 years ago

What a weird thing.

LGTM!

lukeed commented 7 years ago

I'm traveling back home, only 1 flight left. I'll be able to take a look at this then, but so far looks good.

Thanks !