Optimizing Code Performance and Memory Usage Using performance.now() Function

Measuring code execution time and monitoring memory usage are essential for evaluating and optimizing a program's performance. In this article, we will explore methods for measuring code execution time, monitoring memory usage, and optimizing both aspects.

Measuring Code Execution Time

To measure code execution time, you can use the performance.now() method, which returns a timestamp representing the current time. By calculating the difference between the start and end timestamps, you can determine the execution time.

performance.now()

function exampleFunction() {
    // 코드 실행 시작 시간 기록
    const startTime = performance.now();

    // 여기에 코드 실행

    // 코드 실행 종료 시간 기록
    const endTime = performance.now();

    // 실행 시간 계산 (밀리초로 나타남)
    const executionTime = endTime - startTime;

    console.log(`코드 실행 시간: ${executionTime} 밀리초`);
}


Monitoring and Optimizing Memory Usage

To monitor memory usage, you can utilize the developer tools in web browsers. Most browsers like Chrome, Firefox, and Safari provide memory profiling features.

  1. Memory Profiling Using Chrome Developer Tools
  • Open the developer tools in Chrome by pressing the F12 key.
  • Navigate to the "Performance" tab and click on the "Record" button to start performance profiling.
  • After executing the code, click the "Stop" button to end the profiling.
  • In the "Memory" section, you can find information related to memory usage.
  1. Identifying Memory Leaks
  • Memory leaks refer to the continuous increase in memory due to unintended memory usage in a program. You can capture memory snapshots in the "Memory" tab of the developer tools to identify memory leaks.

By analyzing the sample code, it was possible to enhance code performance and optimize memory usage through measuring code execution time. It was discovered that string operations, due to their immutability, require creating new strings for each operation. However, using arrays can reduce memory usage.

Realizing that substantial theoretical knowledge is required for optimizing code performance and memory usage, it became evident during the process of measuring code performance and monitoring memory usage.

performance.now()