Module 1
Strings and StringBuilders
Memory Analysis


CC315

Where We Are

  • Strings are natural choice
  • Strings are immutable
  • We can work around that
    • Java: StringBuilder Class
    • Python: Array
Psuedocode Comparison

    function ENCODER(TEXT,X) // General: Strings
        //TEXT is the text to encode
        //X is the offset
        ENC = ""
        loop I from 1 to LENGTH of TEXT
            CURRENT = TEXT[I]
            IF CURRENT IS A LETTER
                CHAR_ENC = GET X-th CHAR after CURRENT
                ENC += CHAR_ENC
            ELSE
                ENC += '*'
        end loop
        return ENC
    end function
 

    function SBENCODER(TEXT,X) // Java: StringBuilder
        //TEXT is the text to encode
        //X is the offset
        ENC = new StringBuilder()
        loop I from 1 to LENGTH of TEXT
            CURRENT = TEXT[I]
            IF CURRENT IS A LETTER
                CHAR_ENC = GET X-th CHAR after CURRENT
                ENC.append(CHAR_ENC)
            ELSE
                ENC.append('*')
        end loop
        return ENC.toString()
    end function
 

    function ARR_ENCODER(TEXT,X) # Python: Array
        #TEXT is the text to encode
        #X is the offset
        ENC = []
        loop I from 1 to LENGTH of TEXT
            CURRENT = TEXT[I]
            IF CURRENT IS A LETTER
                CHAR_ENC = GET X-th CHAR after CURRENT
                ENC.append(CHAR_ENC)
            ELSE
                ENC.append('*')
        end loop
        return "".join(ENC)
    end function
 

Time Comparison

Memory Analysis

  • Language garbage collection
  • Language's compensation
    for immutable strings
  • Where does that leave us?

To String or Not To String

  • Good: Strings are okay
  • Bad: String modification
  • It depends!