Escape from code illusion

Sometimes we fall into illusion of performant code. It happened to me recently. This is what the case.

Problem: Identify unique values in an array of values where all items appear exactly twice but one. 

Super simple right? I wrote the following two different solutions.

Solution 1:
        var singleNumber = function(nums) {
    return Object.keys(nums.reduce((acc, item) => {
       if(typeof(acc[item]) !== 'undefined') {
           delete acc[item];
       } else {
           acc[item] = item;
       }
        return acc;
    },{}))[0];
};

Solution 2: 

     var singleNumber = function(nums) {
        return nums.reduce((acc, item) => acc ^ item);
     };

 

What your choice? mine was the first one. When I compare the performance of both the codes, the following is the result.

Solution 1:


Solution 2: 

OMG!, Validate your code before deciding what is performant. That doesn't stop there. Tried to check what is wrong and written this.

Solution 3: 

var singleNumber = function(nums) {
    return nums.reduce((acc,num) => {
        acc=acc^num; return acc;
    }, 0);
};

and now the result is this.


 How cool. Reduced number of lines doesn't mean performant code. :-)


Comments

Popular posts from this blog

Recursion

LinkedList - React Show

Train Game