I'm working on a JavaScript function that compares two arrays of strings to see if their concatenated contents are equal. I've written two versions of the function, one using explicit variables and another more concise version. Surprisingly, I noticed a slight performance difference between the two implementations.
Here are the two versions of the function:
version 1
var arrayStringsAreEqual = function(word1, word2) {
let a = word1.join('');
let b = word2.join('');
if (a == b) {
return true;
} else {
return false;
}
};
version 2
var arrayStringsAreEqual = function(word1, word2) {
return word1.join('') == word2.join('');
};
Could someone explain why there might be a performance difference between these two versions, even though they're functionally equivalent? Is it related to how JavaScript engines optimize code, or are there other factors at play?
While both versions achieve the same result, I found that version 1 (with explicit variables) is marginally faster in some cases. I'm curious why this might be the case.
Usually using a variable is an additional overhead, but in your case Chrome was able to provide the same performance. But if a variable is reused, that could actually boost performance. So the rule could be - don't create unnecessary variables.
Also note that JS engine could optimize code while compiling so in reality your both examples could be exactly the same after being compiled.
If you create a variable it could be considered a write operation, but write operations are anything that mutates data or creates new one, in your case you join an array and this is a quite big write operation that stores the result as a temporary string. So when you assign this string to a real variable you add almost nothing to the already tremendous overhead. The less write operations the faster code. But that's about constant factors in an algorithm. I suggest to learn about time complexity and big O notation.