Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- let arr = [];
- resetArray = () => {
- arr = [];
- for (let i = 0; i < 1000; i++) {
- arr.push({
- item_metadata: {
- tags: [
- 'tag1',
- 'tag2',
- 'tag3',
- 'tag4',
- 'tag5',
- 'tag6',
- 'tag7',
- 'tag8',
- 'tag9',
- 'tag10',
- ],
- },
- });
- }
- }
- const foreachWay = () => {
- arr.forEach((el) => {
- el.item_metadata.tags.forEach((e) => {
- e = '';
- });
- });
- };
- const forWay = () => {
- for (let i = 0; i < arr.length; i++) {
- for (let j = 0; j < arr[i].item_metadata.tags.length; j++) {
- arr[i].item_metadata.tags[j] = '';
- }
- }
- }
- function benchmarkFunction(func, args, iterations = 100) {
- console.log('populating data...')
- resetArray();
- console.log(`benchmarking(${func.name}, iterations: ${iterations})`);
- console.log('\twarming up');
- // Warm-up run
- for (let i = 0; i < 10; i++) {
- // @ts-expect-error unknown
- func(...args);
- }
- console.log('\tbenchmarking');
- const start = performance.now();
- for (let i = 0; i < iterations; i++) {
- // @ts-expect-error unknown
- func(...args);
- }
- const end = performance.now();
- console.log('\tfinished !\n');
- return end - start;
- }
- const iterations = 10;
- console.log('Benchmarking foreachWay');
- const time1 = benchmarkFunction(foreachWay, [], iterations);
- console.log('Benchmarking forWay');
- const time2 = benchmarkFunction(forWay, [], iterations);
- console.log(`foreachWay: ${time1}ms`);
- console.log(`forWay: ${time2}ms`);
- // output:
- /*
- Benchmarking foreachWay
- populating data...
- benchmarking(foreachWay, iterations: 10)
- warming up
- benchmarking
- finished !
- Benchmarking forWay
- populating data...
- benchmarking(forWay, iterations: 10)
- warming up
- benchmarking
- finished !
- foreachWay: 0.07125000000000092ms
- forWay: 0.23512500000000003ms
- */
Advertisement
Add Comment
Please, Sign In to add comment