exapsy

Untitled

Oct 18th, 2024
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.94 KB | None | 0 0
  1. let arr = [];
  2.  
  3. resetArray = () => {
  4. arr = [];
  5. for (let i = 0; i < 1000; i++) {
  6. arr.push({
  7. item_metadata: {
  8. tags: [
  9. 'tag1',
  10. 'tag2',
  11. 'tag3',
  12. 'tag4',
  13. 'tag5',
  14. 'tag6',
  15. 'tag7',
  16. 'tag8',
  17. 'tag9',
  18. 'tag10',
  19. ],
  20. },
  21. });
  22. }
  23. }
  24.  
  25. const foreachWay = () => {
  26. arr.forEach((el) => {
  27. el.item_metadata.tags.forEach((e) => {
  28. e = '';
  29. });
  30. });
  31. };
  32.  
  33. const forWay = () => {
  34. for (let i = 0; i < arr.length; i++) {
  35. for (let j = 0; j < arr[i].item_metadata.tags.length; j++) {
  36. arr[i].item_metadata.tags[j] = '';
  37. }
  38. }
  39. }
  40.  
  41.  
  42. function benchmarkFunction(func, args, iterations = 100) {
  43. console.log('populating data...')
  44. resetArray();
  45.  
  46. console.log(`benchmarking(${func.name}, iterations: ${iterations})`);
  47. console.log('\twarming up');
  48. // Warm-up run
  49. for (let i = 0; i < 10; i++) {
  50. // @ts-expect-error unknown
  51. func(...args);
  52. }
  53.  
  54. console.log('\tbenchmarking');
  55. const start = performance.now();
  56. for (let i = 0; i < iterations; i++) {
  57. // @ts-expect-error unknown
  58. func(...args);
  59. }
  60. const end = performance.now();
  61. console.log('\tfinished !\n');
  62. return end - start;
  63. }
  64.  
  65. const iterations = 10;
  66.  
  67.  
  68. console.log('Benchmarking foreachWay');
  69. const time1 = benchmarkFunction(foreachWay, [], iterations);
  70. console.log('Benchmarking forWay');
  71. const time2 = benchmarkFunction(forWay, [], iterations);
  72.  
  73. console.log(`foreachWay: ${time1}ms`);
  74. console.log(`forWay: ${time2}ms`);
  75.  
  76. // output:
  77. /*
  78. Benchmarking foreachWay
  79. populating data...
  80. benchmarking(foreachWay, iterations: 10)
  81. warming up
  82. benchmarking
  83. finished !
  84.  
  85. Benchmarking forWay
  86. populating data...
  87. benchmarking(forWay, iterations: 10)
  88. warming up
  89. benchmarking
  90. finished !
  91.  
  92. foreachWay: 0.07125000000000092ms
  93. forWay: 0.23512500000000003ms
  94. */
Advertisement
Add Comment
Please, Sign In to add comment