Can someone explain this performance result?

-1

I have the following snippets in JavaScript:

Script 1: multiple return

function prueba(valor) {
  if (valor == 1) {
    return '1';
  } else if (valor == 2) {
    return '2';
  } else if (valor == 3) {
    return '3';
  }
  return '';
}
prueba(3);

Script 2: a single return

function prueba(valor) {
  var devolucion = '';
  if (valor == 1) {
    devolucion = '1';
  } else if (valor == 2) {
    devolucion = '2';
  } else if (valor == 3) {
    devolucion = '3';
  }
  return devolucion;
}
prueba(3);

I do a performance test and it appears to me that the script with a return unique is faster than the script with multiple return , as you can see in this image:

Why does that happen? Can someone explain this performance result?

    
asked by Johny Rooke 21.09.2017 в 12:58
source

1 answer

0

A possible explanation may be how Javascript behaves internally when doing return .

First, in the Script 2 when you perform a return on a literal (that is, the number you return) internally you must reserve memory to create a temporary variable that references the literal, a Once the temporary variable has been used, it should be discarded.

On the other hand, if you look at the Script 1 code that uses the return variable, this variable is declared as var devolución which Javascript will interpret as a global variable, that is, the memory will be reserved only once and in the return only a reference will be passed to the reserved memory area. This memory area, unlike the first case mentioned, should not be destroyed once it is used, as it is not a temporary variable.

    
answered by 21.09.2017 в 15:08