Which of these functions is the fastest and why? (JavaScript)

Hello, I tried to use performance.now() to find out which of these three functions is the fastest, but unfortunately I did not get a result.

Can someone explain me why one function is faster then the other?

var subtract = {
	sub: function(a, b) { return a - b; }
};

// Variant 1
(function() {
	var numb = 1;
	return {
		sub: function(a, b) { return subtract.sub(a, b); }
	};
})();

// Variant 
(function(subtract) {
	var numb = 1;
	return 
	{
		sub: function(a, b) { return subtract.sub(a, b); }
	};
})(subtract);

How did you try to use performance.now() to test?

var start = performance.now();
function
var duration = performance.now() - start;
console.log(duration);

tried to get the time it needs, but I think its not a good approach

To be honest, it was just an attempt, I’m still pretty new to the field of programming. Otherwise, I wouldn’t have asked.

Answering your question, variant 3 would be the quickest because it will not return an object, more about it here:

Normally you want to run function couple times and then calculate average, I normally use this:

const benchmark = (fn, runs = 100) => {
    let i = runs;
    const output = [];
    while (i > 0) {
        const ts = performance.now();
        fn();
        const te = performance.now();
        output.push(te - ts);
        i--;
    }
    return {
        runs,
        max: Math.max(...output),
        min: Math.min(...output),
        avg: output.reduce((a, b) => a + b) / runs,
    };
};

If you want something more sophisticated, then this:
https://jsperf.com/

@snigo got there first, but was going to say, this isn’t going to tell you anything, you need to run it hundreds/thousands of times to get any reasonable comparison. And in this case it’s almost completely pointless, because it’s so simple: just write

function sub(a, b) {
  return a - b;
}

If you want a subtract function. That is extremely readable and extremely fast. Any optimisation is faintly ridiculous here, particularly given it’s entirely based on how a particular JS engine is implemented.

Optimising your code in the way you’re trying to do is [imo] a fools errand – JS is a very high level language with multiple implementations, and trying to second guess the specific compiler/interpreter being used is not a great idea, particularly if you’re only starting to learn programming.