我是JS世界的新手,我想知道这两种方法中哪一种更有效,并且会消耗更少的内存?在第一种方法中,变量queryParams
和返回值都会消耗内存吗?
在JS中检查内存消耗的一些好工具/方法有哪些?
方法 1
getQueryParamsForPreviousUrl(): string {
let queryParams: string = '';
if (this._currentUrl) {
const index = this._currentUrl.indexOf('?');
if (index !== -1) {
queryParams = this._currentUrl.slice(index);
}
}
return queryParams;
}
方法 2
getQueryParamsForPreviousUrl(): string {
if (this._currentUrl) {
const index = this._currentUrl.indexOf('?');
if (index !== -1) {
return= this._currentUrl.slice(index);
}
}
return '';
}
问:在第一种方法中,变量queryParams
和返回值都会消耗内存吗?
答:queryParams
肯定会消耗一些内存。这里将发生的情况是,当您的代码运行方法getQueryParamsForPreviousUrl(...)
时,变量将被声明并存储在进程的stack
内存中。
一旦您的代码退出,queryParams
将被标记为"符合垃圾回收条件",然后在将来的某个时间点,垃圾回收器将释放消耗的内存。