• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (C) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16export class objectToMemorySize {
17  private seen = new WeakSet();
18
19  /**
20   * objectToSize
21   *
22   * number:8 bytes (64-bit storage)
23   * String:一characters 2 bytes
24   * Boolean:4 bytes
25   *
26   * @param object
27   */
28  objectToSize(object: any): any {
29    const objType = typeof object;
30    switch (objType) {
31      case 'string':
32        return object.length * 2;
33      case 'boolean':
34        return 4;
35      case 'number':
36        return 8;
37      case 'object':
38        if (Array.isArray(object)) {
39          return object.map(this.objectToSize).reduce((res, cur) => res + cur, 0);
40        } else {
41          return this.sizeOfObj(object);
42        }
43      default:
44        return 0;
45    }
46  }
47
48  sizeOfObj(object: any): number {
49    if (object === null) return 0;
50
51    let bytes = 0;
52    // The key in the object also takes up memory space
53    const props = Object.keys(object);
54    for (let i = 0; i < props.length; i++) {
55      const key = props[i];
56      // Whether the value is repeated or not, the key needs to be calculated
57      bytes += this.objectToSize(key);
58      if (typeof object[key] === 'object' && object[key] !== null) {
59        // 这里需要注意value使用相同内存空间(只需计算一次内存)
60        if (this.seen.has(object[key])) continue;
61        this.seen.add(object[key]);
62      }
63      bytes += this.objectToSize(object[key]);
64    }
65    return bytes;
66  }
67}
68