Skip to content

Improve performance of getFreeSpace() function #5

Description

@MG665

The getFreeSpace() function in the plugin code is currently causing performance issues due to the string generation operation in the setItem() method. After researching the issue, I found a way to optimize the function and make it more efficient.

I suggest replacing the current implementation of getFreeSpace() with the following updated code:

   function* getFreeSpace() {
  // The closer we are to the real size, the faster it returns.
  let maxCharSize = 10485760; // ~10MBytes
  let minCharSize = 0;
  const stopSize = 1024 * 1; // ~ 1KBytes
  const testKey = 'testQuota';
  const testValue = '1'.repeat(maxCharSize); // pre-generate string
  let lastRunFailed = false;
  do {
    let trySize = 1;
    try {
      trySize = Math.ceil((maxCharSize - minCharSize) / 2) + minCharSize;
      window.localStorage.setItem(testKey, testValue.substring(0, trySize)); // use substring
      minCharSize = trySize;
      lastRunFailed = false;
    } catch {
      maxCharSize = trySize - 1;
      lastRunFailed = true;
    }
    yield minCharSize + testKey.length - (lastRunFailed ? 1 : 0);
  } while (maxCharSize - minCharSize > stopSize);
  window.localStorage.removeItem(testKey);
  return minCharSize + testKey.length - (lastRunFailed ? 1 : 0);
}

The main changes made to the function are:

  • Using a pre-generated string of 1s with the maximum possible length, instead of generating a new string on each iteration of the loop
  • Using the substring() method to set the value in localStorage, instead of generating a new string
  • Changing the maxCharSize variable from a constant to a regular variable, to allow for reassignment
  • Adding lastRunFailed ? 1 : 0 to the yield statement to adjust the returned value based on whether the last run was successful or not

These changes should help improve the performance of the function by reducing the amount of time spent generating strings. Plugin was tested and is working correctly, the performance of the getFreeSpace function has been improved by ~2x (31ms instead of 63ms+)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions