首页 > 解决方案 > HereMaps Javascript MemoryLeak?

问题描述

我目前正试图在我的角度应用程序中找到一些潜在的内存泄漏,并找到了一些应该与 hereMap 相关的东西,我在一个组件中使用了这些东西。这是这种情况:

我有一个包含两个组件的 Angular 12 SPA:

ComponentA - 完全空的角度组件 - 仅用于远离组件 B

ComponentB - 使用 hereMap 的组件。

当将路由从组件 A 切换到 B 到 AI 时,垃圾收集器会在一段时间后返回到 A 或单击 DevTools 中的“收集垃圾”时移除大部分分配的内存。

以下是让我发疯的原因:

每次当我使用 ComponentB 去路线时,似乎 mapsjs-core.js 添加了一个新的 TileManager,它永远留在内存中并保存大量的对象和数组(每次 3.5k 数组和 10k 对象)加起来每次喜欢 3-5mb 内存。

堆快照

这些对象包括多个 TileManager 实例中的纹理、网格、盾牌等(在创建 ComponentB 的新实例 3 次后的 TileManager_0、TileManager_1、TileManager_2)。

调用 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();
    }

}

标签: javascriptangularmemory-leakshere-api

解决方案


我们对简单的 vanilla Javascript 应用程序和 Angular 应用程序进行了性能测试。并且对象正在根据需要从堆内存中释放。请查找以下附加结果。

在此处输入图像描述

请注意,Map 不应该释放任何其他对象,而是释放自身,因此应用程序必须显式释放应用程序创建的任何其他资源。原因很简单:让我们以一个应用程序为例,它创建了一个提供者并填充了它,应用程序可能决定重用这个提供者,但处置地图。请按照以下链接获取最佳实践。

1>HERE Maps API for Javascript 的工作。 https://developer.here.com/documentation/maps/3.1.25.0/dev_guide/topics/get-started.html

2>角度示例。

https://developer.here.com/blog/display-here-maps-angular-web-application(请在angular的ngOnDestroy方法中添加对heremap对象的处理,即this.map.dispose())

3>最佳实践。

https://developer.here.com/documentation/maps/3.1.25.0/dev_guide/topics/best-practices.html


推荐阅读