代码之家  ›  专栏  ›  技术社区  ›  mljrg

Elixir/Erlang中字符串的长度和大小需要解释

  •  2
  • mljrg  · 技术社区  · 6 年前

    s 是一个包含4096个字符的字符串

    iex(9)> s = String.duplicate("x", 4096)
    ... lots of "x"
    iex(10)> String.length(s)
    4096
    

    iex(11)> :erts_debug.size(s)
    6 # WHAT?!
    

    为什么 s2 是一根比 S

    iex(13)> s2 = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20"
    "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20"
    iex(14)> String.length(s)
    50
    

    但它的大小有3个字比 S ?

    iex(15)> :erts_debug.size(s2)
    9 # WHAT!?
    

    为什么这些弦的大小和它们的长度不匹配?

    谢谢

    1 回复  |  直到 6 年前
        1
  •  3
  •   Hauleth    6 年前

    this question . 引用 size/1 文件:

    %% size(Term)
    %%  Returns the size of Term in actual heap words. Shared subterms are
    %%  counted once.  Example: If A = [a,b], B =[A,A] then size(B) returns 8,
    %%  while flat_size(B) returns 12.
    

    Erlang documentation about bitstrings implementation .


    因此在第一种情况下,字符串太大,无法单独放在堆中,因此它使用 refc binaries 存储在 堆栈 堆上只有指向给定二进制文件的指针。

    在第二种情况下,字符串短于64字节,它使用 heap binaries 它只是直接存储在堆中的字节数组,因此 8 bytes per word (64-bit) * 9 = 72 Erlang uses 3..6 words per binary + data , where data can be shared .