Forked from doman89/doman-code-metoda-map-a-petle-for.js
Last active
October 9, 2022 10:07
-
-
Save 403-html/749ad529a2fd2027ff277871e09f36dc to your computer and use it in GitHub Desktop.
Doman Code - forking
This file contains hidden or 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
// count time needed to execute a function | |
// precisition is 0.0001 ms | |
const countTime = (func) => { | |
const startTime = performance.now(); | |
func(); | |
const endTime = performance.now(); | |
const timeNeeded = endTime - startTime; | |
console.log(`${func.name} needed ${timeNeeded.toFixed(4)} ms`); | |
} | |
const lengthOfArray = 10 ** 7; | |
const exampleArray = Array.from({ length: lengthOfArray }, () => Math.random().toString(36).substring(2, 12)); | |
const standardForLoop = () => { | |
const resultArrayClassicFor = []; | |
for (let index = 0; index < exampleArray.length; index++) { | |
const arrayElement = exampleArray[index]; | |
const recommendString = `Polecam ${arrayElement}`; | |
resultArrayClassicFor.push(recommendString); | |
} | |
return resultArrayClassicFor; | |
} | |
const standardForOfLoop = () => { | |
const resultArrayForOf = []; | |
for (const arrayElement of exampleArray) { | |
const recommendString = `Polecam ${arrayElement}`; | |
resultArrayForOf.push(recommendString); | |
} | |
return resultArrayForOf; | |
} | |
const standardMapLoop = () => { | |
const resultArrayMap = exampleArray.map((arrayElement, index, currentArray) => { | |
const recommendString = `Polecam ${arrayElement}`; | |
return recommendString; | |
}); | |
return resultArrayMap; | |
} | |
const myFirstMethod = () => { | |
const resultArray = Array.from(exampleArray, (element) => `Polecam ${element}`); | |
return resultArray; | |
} | |
const mySecondMethod = () => { | |
const resultArray = exampleArray.reduce((acc, element) => { | |
acc.push(`Polecam ${element}`); | |
return acc; | |
}, []); | |
return resultArray; | |
} | |
const main = () => { | |
countTime(standardForLoop) | |
countTime(standardForOfLoop); | |
countTime(standardMapLoop); | |
countTime(myFirstMethod); | |
countTime(mySecondMethod); | |
} | |
main(); | |
// output | |
// standardForLoop needed 819.9759 ms | |
// standardForOfLoop needed 801.9562 ms | |
// standardMapLoop needed 931.0525 ms | |
// myFirstMethod needed 865.7983 ms | |
// mySecondMethod needed 719.9408 ms |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment