javascript - 函数在内存中的大小

标签 javascript function memory

我一直在使用 sizeof.js 探索 javascript 中各种对象的大小。当我检查一个函数的大小时,无论该函数包含多少行代码,我都得到零字节。例如:

alert(sizeof(
  function(){
    return 1;
  }
));

这将返回零大小。即使我为该函数提供多行代码,我得到的大小也是零字节。存储字符串所需的内存量取决于字符串的长度。但是函数的复杂性或大小似乎无关紧要。为什么会这样?

最佳答案

如果查看sizeof库的源代码,可以发现对象类型function在sizeof库中没有处理,所以默认大小0 返回。

/*

sizeof.js

A function to calculate the approximate memory usage of objects

Created by Stephen Morley - http://code.stephenmorley.org/ - and released under
the terms of the CC0 1.0 Universal legal code:

http://creativecommons.org/publicdomain/zero/1.0/legalcode

*/

/* Returns the approximate memory usage, in bytes, of the specified object. The
 * parameter is:
 *
 * object - the object whose size should be determined
 */
function sizeof(object){

  // initialise the list of objects and size
  var objects = [object];
  var size    = 0;

  // loop over the objects
  for (var index = 0; index < objects.length; index ++){

    // determine the type of the object
    switch (typeof objects[index]){

      // the object is a boolean
      case 'boolean': size += 4; break;

      // the object is a number
      case 'number': size += 8; break;

      // the object is a string
      case 'string': size += 2 * objects[index].length; break;

      // the object is a generic object
      case 'object':

        // if the object is not an array, add the sizes of the keys
        if (Object.prototype.toString.call(objects[index]) != '[object Array]'){
          for (var key in objects[index]) size += 2 * key.length;
        }

        // loop over the keys
        for (var key in objects[index]){

          // determine whether the value has already been processed
          var processed = false;
          for (var search = 0; search < objects.length; search ++){
            if (objects[search] === objects[index][key]){
              processed = true;
              break;
            }
          }

          // queue the value to be processed if appropriate
          if (!processed) objects.push(objects[index][key]);

        }

    }

  }

  // return the calculated size
  return size;

}

您可以看到 size 被初始化为值 0 并且类型 function 没有在 switch 中处理> 语句,因此它将始终为函数返回 0

关于javascript - 函数在内存中的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26856783/

相关文章:

JavaScript .forEach() 和 .splice() 未按预期工作

javascript - typeerror undefined 不是一个函数 liferay

java - 使用 JVM 内存默认值运行 Java Web 应用程序

javascript - Crypto-JS 总是返回新的哈希值

javascript - bacon.js - 忽略流中的某些值

javascript:函数也是对象——对还是错?

C - 将未初始化的变量传递给函数

python - (TypeError : expected string or bytes-like object) when calling function in Django

ios - 这些闭包中的保留周期有什么区别?标准闭包与对象初始化闭包

docker - 内存使用差异 : cgroup memory. usage_in_bytes 与 Docker 容器内的 RSS