I would expect more highly nested lists, being deeper and more complex than flatter lists, to take up more space (bytecount) and take more time and memory to operate on in general. Consider the following.
Let's make a highly nested list of integers and a list with the same elements but flatter.
a1 = RandomInteger[9, {20, 30, 40, 50}];
a2 = Flatten[a1, {{1}, {2}, {3, 4}}];
Both are packed arrays.
a1 // PackedArrayQ
a2 // PackedArrayQ
(*True*)
(*True*)
They have nearly the same bytecount.
a1 // ByteCount
a2 // ByteCount
(*9600224*)
(*9600216*)
Let's perform a nesting operation on both. The time taken and memory involved is nearly the same (the timing was even closer in different trials).
h[a_] := Outer[Append, a, Last /@ a, 1]
h[a1] // MaxMemoryUsed // AbsoluteTiming
h[a2] // MaxMemoryUsed // AbsoluteTiming
(*{0.097976, 208425704}*)
(*{0.089271, 208422184}*)
The output lists have nearly the same bytecount as well, but neither is packed.
h[a1] // ByteCount
h[a2] // ByteCount
(*198490600*)
(*198487400*)
h[a1] // PackedArrayQ
h[a2] // PackedArrayQ
(*False*)
(*False*)
Even if we vastly change how deeply nested the original list a1
is and the number of elements each level has, and then compare it to more flattened versions a2
and a3
, we get similar results. For example, the same conclusions can be seen from the following.
a1 = RandomInteger[9, {150, 100, 80}];
a2 = Flatten[a1, {{1}, {2, 3}}];
a3 = Flatten[a1];
a1 // ByteCount
a2 // ByteCount
a3 // ByteCount
(*9600216*)
(*9600208*)
(*9600200*)
h[a1] // MaxMemoryUsed // AbsoluteTiming
h[a2] // MaxMemoryUsed // AbsoluteTiming
(*{0.928319, 1487693704}*)
(*{0.916964, 1487305936}*)
h[a1] // ByteCount
h[a2] // ByteCount
(*1477273280*)
(*1477093280*)
Why is this?