Skip to content
Tcl Source Code Ticket Change Details
Login

Ticket Change Details

Overview

Artifact ID: db5e1d016d269be2c94a72da40f0b08e09c0d256
Ticket: 781746ffffffffffffffffffffffffffffffffff
Memory leak with arrays whose elements are lists
User & Date: msofer on 2003-08-02 05:37:44
Changes

  1. assignee changed to: "msofer"
  2. closedate changed to: "2003-08-01T22:37:44"
  3. closer changed to: "msofer"
  4. icomment:
    Logged In: YES 
    user_id=148712
    
    This may not really a bug in tcl, but rather pilot error? Or
    insufficient docs? Or one of those cases where knowledge of
    the internals makes a difference (performance, memory).
    
    First, note that  your script runs much better if you replace 
        set a($count) [concat $element $count]
    in the creation loop with the two lines
        set a($count) $element
        lappend a($count) $count
    or else with
        set a($count) [concat $element [list $count]]
    Note that these are (in this case) fully equivalent, except
    for the memory requirements.
    
    I'll try to explain the difference in memory requirements,
    and let you decide where the bug is.
    
    The problem is caused by the fact that [concat] returns a
    new Tcl_Obj; if any of the lists to be concatenated is *not*
    a pure list (which is your case), a string representation is
    returned.  Your script hence defines all array elements
    initially from their string internal representation. 
    
    The first loop then converts a copy (recordLine) of each
    $a($count) to a list when requesting its llength; but
    recordLine's is promptly discarded at the next iteration. So
    you have 20000 string reps and one list with 100 elements.
    The second loop converts every array element to list
    representation; you have then 20000 Tcl_Obj for the
    $a($count), each with both a string and a list
    representation, plus 2000000 Tcl_Obj for the elements of
    $a($count) ... boom.
    
    So: why doesn't my little change boom too? Tcl's internal
    are clever about sharing Tcl_Obj's - in the second and third
    versions, the core recognizes that many of those 2000000
    elements are repeated, and manages with 20000 objects (each
    with a ref erence count of 100) for a total of 40000.
    
    But the core is not clever enough to notice that the 2000000
    elements can be represented so sparingly in your script,
    which creates them afresh by splitting the string values of
    the $a($count). My versions never destroyed the relationship
    to begin with, yours "went out of its way" to hide it. 
    
    I do hope the explanation is understandable ...
    
    
  5. login: "msofer"
  6. mimetype: "text/plain"
  7. username: "msofer"