2

I don't need a return value from the related function, which method is faster on the system run: end the function with return without value or do not use return anywhere?

Using return without any value:

function saveData(save){
   save(newData);

   return; //return without any value
}


Not using return anywhere:

function saveData(save){
   save(newData);

   //There is no return anywhere
}


although there is no specific speed difference, this info will be useful in large-scale use.

  • But if you don't return the Promise chain, then errors will result in unhandled rejections, right? Might not be a great idea in some circumstances – CertainPerformance Dec 06 '18 at 06:10
  • See T.J. Crowder's answer [here](https://stackoverflow.com/questions/17337064/does-every-javascript-function-have-to-return-a-value) for some related info – CertainPerformance Dec 06 '18 at 06:12
  • 1
    I'd assume after JIT or any other optimization that both functions are executed the same way. This is not something you should worry about. – Felix Kling Dec 06 '18 at 06:41
  • In your context, you are calling an async method. In the first code, you are using a `return` statement after the async call thus you are ending the function before ending the async call. It may not be what you are looking for. – Weedoze Dec 06 '18 at 06:42
  • Instead of using a callback you should use the Promise and use `return asyncGetData();` – Weedoze Dec 06 '18 at 06:43
  • Having a `return;` statement that returns nothing at the end of a function is pointless and unnatural. But if you are working with promises, you should return a promise. – JLRishe Dec 06 '18 at 06:48

1 Answers1

-1

Short Answer: It is faster to explicitly return for short loops (1000 iterations). But if your loop iterates 100000 times, then it is faster not to return from functions.

I ran a Javascript bench tests using JSBEN.CH

var sum = 0;
for(var i=0; i<1000; i++) {
    sum += is_even(i) ? 1: 0;
}
console.log(sum);

The function is_even() is defined here:

without return

function is_even(n) {
    if(n%2==0) { return true; }   
             // no return if n is odd.
             // default return is undefined
}

with return;

function is_even(n) {
    if(n%2==0) { return true; }   
       return;
}

The test reported (with return) block to be faster.

Comparison result

Then I increased the number of iterations in the for-loop, and got a reversed result.

var sum = 0;
for(var i=0; i<100000; i++) {
    sum += is_even(i) ? 1: 0;
}
console.log(sum);

In that case, the benching tool reported that the function with no return; is faster.

Ahmad
  • 12,336
  • 6
  • 48
  • 88
  • 1
    Any difference you measure is likely arbitrary. I'd assume after JIT or any other optimization that both functions look the same. – Felix Kling Dec 06 '18 at 06:40