Tcl 中数字与字母数字的预期内存占用

Expected memory footprint of numbers vs alphanumerics in Tcl

在Tcl中是辅助,"everything is a string"。但话又说回来,它并不是 100% 完全一样(因此有闪烁的效果)。我的问题是:假设我在列表中有以下值:

list "12" 14 2a "1a"

我的期望是,如果 "everything is a string",为所有 4 个元素分配的内存应该相同(根据 spec/expected 行为),因为我们正在查看长度为的 4 个字符串实例2.
这是一个正确的假设吗?

这些值可能会以字符串形式开始(由于文字共享的可能性,不能完全确定会发生这种情况)。让我们仔细看看(如果你自己这样做,tcl::unsupported::representation 命令仅在 8.6 中并且 never 修改正在查看的对象;我放了一个 ;format x 在第一行,以确保我们不会得到任何意外的转化)。

% set value [list "12" 14 2a "1a"];format x
x
% tcl::unsupported::representation [lindex $value 0]
value is a pure string with a refcount of 2, object pointer at 0x100874070, string representation "12"
% tcl::unsupported::representation [lindex $value 1]
value is a pure string with a refcount of 2, object pointer at 0x1008741c0, string representation "14"
% tcl::unsupported::representation [lindex $value 2]
value is a pure string with a refcount of 2, object pointer at 0x100874c40, string representation "2a"
% tcl::unsupported::representation [lindex $value 3]
value is a pure string with a refcount of 2, object pointer at 0x1008743d0, string representation "1a"
% tcl::unsupported::representation $value
value is a list with a refcount of 4, object pointer at 0x100874910, internal representation 0x1008eb050:0x0, string representation "12 14 2a 1a"

所以是的,这些值几乎相同。它们中的任何一个都没有内部表示,并且每个使用的字符串表示是一个分配为 3 个字节长的缓冲区(一个用于每个字符,一个用于终止 NUL 字节)。然而,列表本身有一个字符串表示(以及它的内部列表代表),尽管没有被要求提供一个;那是因为您使用的是文字列表,而 Tcl 的编译器将其优化为单个文字,因为这通常是正确的做法。