Pritam Bohra
Pritam Bohra

Reputation: 4319

Which function is more efficient with respect to memory consumption?

I am new to the world of JS and I want to know which of the 2 methods is more efficient and will consume less memory? Will variable queryParams and the returned value both consume memory in the first method?

What are some of the good tools/ways to check memory consumption in JS?

Method 1

getQueryParamsForPreviousUrl(): string {
    let queryParams: string = '';

    if (this._currentUrl) {
      const index = this._currentUrl.indexOf('?');

      if (index !== -1) {
        queryParams = this._currentUrl.slice(index);
      }
    }

    return queryParams;
  }

Method 2

getQueryParamsForPreviousUrl(): string {

    if (this._currentUrl) {
      const index = this._currentUrl.indexOf('?');

      if (index !== -1) {
        return= this._currentUrl.slice(index);
      }
    }

    return '';
  }

Upvotes: 0

Views: 1728

Answers (1)

Samuel Toh
Samuel Toh

Reputation: 19248

Q: Will variable queryParams and the returned value both consume memory in the first method?

A: queryParams will definitely consume some memory. What will happen here is that while your code is running method getQueryParamsForPreviousUrl(...), the variable will be declared and store within the process's stack memory.

Once your code exits, queryParams will be marked as been "eligible for garbage collection", then some point in the future the consumed memory will be freed by the garbage collector.

Upvotes: 2

Related Questions