【发布时间】:2021-06-16 16:02:00
【问题描述】:
我目前正试图在我的 Angular 应用程序中找到一些潜在的内存泄漏,并找到了一些与 hereMap 相关的内容,我在一个组件中使用了这些内容。 情况是这样的:
我有一个包含两个组件的 Angular 12 SPA:
ComponentA - 完全空的角度组件 - 仅用于远离组件 B
ComponentB - 使用 hereMap 的组件。
当将路由从组件 A 切换到 B 到 A 时,我希望垃圾收集器在一段时间后返回到 A 或单击 DevTools 中的“收集垃圾”时移除大部分分配的内存。
这就是让我发疯的原因:
每次我使用 ComponentB 去路线时,似乎 mapsjs-core.js 添加了一个新的 TileManager,它永远留在内存中并保存大量对象和数组(每次 3.5k 数组和 10k 对象)每次加起来大约 3-5mb 内存。
这些对象包括多个 TileManager 实例中的纹理、网格、盾牌等(TileManager_0、TileManager_1、TileManager_2 在创建 ComponentB 的新实例 3 次后)。
在调用 ComponentB 的 ngOnDestroy 后,ComponentB 不再是内存的一部分,因此处理映射似乎按预期工作。
以下是组件的外观:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-component-a',
templateUrl: './component-a.component.html',
styleUrls: ['./component-a.component.styl']
})
export class ComponentAComponent implements OnInit {
constructor() { }
ngOnInit(): void {
}
}
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-component-b',
templateUrl: './component-b.component.html',
styleUrls: ['./component-b.component.styl']
})
export class ComponentBComponent implements OnInit, AfterViewInit, OnDestroy {
@ViewChild('map') public mapElement: ElementRef;
private map: H.Map;
private platform: H.service.Platform;
constructor() { }
ngOnInit(): void {
this.platform = new H.service.Platform({
apikey: myKey
});
}
ngAfterViewInit() {
const defaultLayers = this.platform.createDefaultLayers();
// Set min and max zoom level
defaultLayers.vector.normal.map.setMax(16);
defaultLayers.vector.normal.map.setMin(2);
// Initialize the map
this.map = new H.Map(
this.mapElement.nativeElement,
defaultLayers.vector.normal.map,
{
zoom: ZoomLevels.ZOOM_MIN_SINGLE_MAP
}
);
}
public ngOnDestroy(): void {
this.map.dispose();
}
}
【问题讨论】:
-
我没有看到你导入 H..?所以它可能只是窗口上的一个对象?如果是这样,它与 Angular(或一般的 GC)无关。它只是一个加载了脚本标签的应用程序,它位于窗口范围内..?
-
你是对的。如此处所述:developer.here.com/documentation/maps/3.1.25.0/dev_guide/topics/…。它只是一个加载的脚本,我为类型定义添加了包npmjs.com/package/@types/heremaps
-
但我本来希望 this.map.dispose() 释放由此地图上下文创建的所有对象。我还认为,使用每个 ComponentB 重新创建 H.service.Platform 可能是一个问题,但即使将平台设置为静态变量并在构造函数中检查 ComponentB.platform 也无济于事
-
它可能正在使用一些内部缓存,它可能会在一次处置时释放一些东西(稍后可能会被收集)。我不认为这是一个问题..
-
会很好,但不知何故,我不认为这只是缓存的“功能”。它保留每个场景并查看每个在内存中创建的内容。换路线13次后,内存从30mb上升到105mb。还发现“Detached WebGLRenderingContext”13 次
标签: javascript angular memory-leaks here-api