Created
September 25, 2023 22:38
-
-
Save italojs/7ed09e07d0db817ab73ea563df3dcb1c to your computer and use it in GitHub Desktop.
map-performance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { performance } = require('perf_hooks'); | |
// Generate a list of products | |
const productArray = Array.from({ length: 1000000 }, (_, i) => ({ | |
id: i, | |
name: `product${i}`, | |
price: i * 0.5 | |
})); | |
// Convert the product list to a Map for faster lookups | |
const productMap = new Map(productArray.map(product => [product.id, product])); | |
// Measure the time taken to find a product by ID in the array | |
const measureLinearSearchTime = () => { | |
const start = performance.now(); | |
productArray.find(product => product.id === 500000); | |
const end = performance.now(); | |
return end - start; | |
}; | |
// Measure the time taken to find a product by ID in the Map | |
const measureMapSearchTime = () => { | |
const start = performance.now(); | |
productMap.get(500000); | |
const end = performance.now(); | |
return end - start; | |
}; | |
console.log(`Busca Linear: ${measureLinearSearchTime()}ms`); | |
console.log(`Busca via Map: ${measureMapSearchTime()}ms`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment