Sanjay
Sanjay

Reputation: 1745

Automatic executing function in Javascript for profiling implementation

Yet another question related to Javascript Profiling. Yes I know there are lots of questions related to Javascript Code profiling and believe me I've gone through lots of them. But I'm not talking about any profiling tools here. I just want to implement a small profiling script for myself, just to aid in my knowledge.

I'm trying to write a simple dummy profiling code for javascript, but couldn't figure out the way to start. What I actually want is any similar function like declare tick function in PHP which executes automatically each time it encounters any statement which is very useful in writing profiling code in PHP.

Is there any function similar to declare in Javascript so that I can implement these functions to profile my code using these functions performance.now(), performance.memory etc. I don't want to use it this way.

var a = performance.now();
// do your stuffs
var b = performance.now();
console.log('It took ' + (b - a) + ' ms.');

I don't think this is practical way to do. Don't want to inject profiling codes into my production scripts.

What I want is to run the profiling code on top of my scripts so it executes automatically every time it encounters the production script functions. Or can you guys please enlighten the better way to start?

P.S. I am not talking about using different browser profiling tools, but talking about small info on how to write a basic profiling tool which will be triggered automatically upon encountering javascript statements or functions.

Upvotes: 2

Views: 308

Answers (3)

Jerome Anthony
Jerome Anthony

Reputation: 8021

AOP is a good. But it is more for cross cutting concerns rather than profiling. The difference is, AOP would exist even with production code, where as profiling code doesn't necessary have to be in the production code. You would have it integrated in your Test environment.

Integrating with a profiler would be much more convenient. The ideal profiler would instrument your code, so you don't have to wrap every function. spy-js is such a good library.

Upvotes: 1

Elad
Elad

Reputation: 1144

Maybe AOP libraries for javascript like meld will help you?

For example:

var timeTook;

var myObject = {
    doSomething: function(a, b) { 
        return a + b;
    }
};

function beforeFunction() {
    timeTook = performance.now();
}

function afterFunction() {
    console.log("It took " + (performance.now() - timeTook));
}

meld.before(myObject, 'doSomething', beforeFunction);
meld.after(myObject, 'doSomething', afterFunction);

See Also this question in SO.

Upvotes: 3

Related Questions