• [Other] An Overview of Arrays and Memory


    One integer takes 32bit in memory, 1 byte = 8bits, therefore one integer takes 4 bytes.

    Now let's assume we have an array: [1,2,3]

      4bytes .   4bytes .  4bytes

    | . | . | . | . | . | . | . | . | . | . | . | . |

         1 .            2 .          3

    It tooks 4 * 3 bytes for three integers in an array. What if we want to add two more integers into the array, how the memory allocate?

       A. it appends another 8 bytes in the end

       B. it recreate an new array with 4 * 5 bytes size. 

    B. is the correct answer. It always create a new larger array and delete the old array. The simple reason for this is because we never know after array, it might have other code:

    var a = [1,2,3]
    var c = 4

      4bytes .   4bytes .  4bytes     4bytes

    | . | . | . | . . | . | . | . | . | . | . | . | . | . | . | . |

         1 .            2 .          3 .        c=4

    It assign 4 bytes to variable c in memory. We cannot simply append more memory after the old array. 

  • 相关阅读:
    IDEA搭建《算法》第四版的开发环境
    tomcat源码环境搭建
    cap定理
    idea jdk 源码搭建
    2020-04-07 学习记录
    idea 格式化代码
    Ajax工作原理
    prototype封装继承
    作用域
    原型链的原理
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10236848.html
Copyright © 2020-2023  润新知