0

I have two functions in a code, one using map() and the other, filter()

const eip = [...new Map(elasticIps.map(e  => [e.publicIp, e])).values()];

const eip = elasticIps.filter((v,i,a)=>a.findIndex(t=>(t.publicIp === v.publicIp))===i)

They both do exactly the same thing for me, but I don't know the best way to find out which is faster

Abhay
  • 3,151
  • 1
  • 19
  • 29
  • 1
    https://developer.mozilla.org/en-US/docs/Web/API/Console/time `console.time()` ? – Mister Jojo Jun 13 '20 at 17:03
  • 3
    Second one uses nested for loop, so it's time complexity will be of order O(n ^ 2) – Code Maniac Jun 13 '20 at 17:05
  • 1
    Question is not related to “functional programming”. Question would be the same for any functions, g and f, for which the result/semantics are the same. – user2864740 Jun 13 '20 at 17:34
  • The “performance“ of this code will also depend on the number of elements. For small sizes it’s not relevant. For large sizes, one is clearly better as the basic complexity is different. I would likely use the first form without additional performance information (indented slightly differently) as it “draws my eyes” to the uniqueness-intent better and might avoid some oops cases for a large number of items. – user2864740 Jun 13 '20 at 17:37
  • 1
    Test with real world data. eg: quicksort can be slower than O(N^2) and O(N^3) algs for specific data sets and requirements. Generally and overall the first one should be best (and it also happens to be the most elegant). Also, if you are in a situation where object initialization and micro-opts becomes a factor (which is kind of unlikely) mutating an object in place instead of the first one will be faster. Even though your syntax is probably the most elegant. – user120242 Jun 13 '20 at 17:37
  • @user120242 ..and this is why there are many more merge sort and derivative implementations :D – user2864740 Jun 13 '20 at 17:44

1 Answers1

1

You can use console.time("label") and console.timeEnd("label") for this.

for ex:

console.time("mapWay")
const eip = [...new Map(elasticIps.map(e  => [e.publicIp, e])).values()];
console.timeEnd("mapWay")

console.time("filterWay")
const eip = elasticIps.filter((v,i,a)=>a.findIndex(t=>(t.publicIp === v.publicIp))===i)
console.timeEnd("filterWay")

you will get results in ms for the label you have set in console.time()

If you want to use some tool to check the benchmark, you can use:

https://jsben.ch/

niranjan_harpale
  • 2,048
  • 1
  • 17
  • 21