Nested Loop becomes slow

Hello I have some nested loop to display files and form menu item.

The part of the code is below.

I found that after runnining the script for a while the display becomes very slow.

Does ksh shell provided any easy way to release variables, reinit, etc.

while [[ $MENU_OPTION == "N" ]];do

    script=0
    town[0]="Start"

    \#Loop to display Menu Item
    \#
    READ_OPTION="N"
    while [[ $READ_OPTION == "N" ]];do
            i=0
            \#Menu Item
            clear
            for file in \`ls x*.txt\`; do
            \{
                    \(\(i=i\+1\)\)

                    town[$i]=$file
                    menuitem=$\(print $\{town[$i]\} | sed -e "s/\\_/ /g"\)
                    mitem=$\(print $menuitem | sed -e "s/\\.txt/ /g"\)
                    if \(\($i<10\)\) then
                            print " \\c"
                    fi
                    echo  "$i ":" $mitem "
            \}
            done
...
done

...

...

..
...

sed may get very slow when you use the /g option, try avoiding it as far as possible, if you can't, try using perl

Not shure if you have choose the most efficient logic in your script but you can try this for the loop:

for file in x*.txt; do {
  i=$(($i + 1))
  if [ "$i" -lt 10 ]  then
    print " \c"
  fi
  mitem=$(print "$file" | sed -e "s/\_/ /g" -e "s/\.txt/ /g")
  echo "$i : $mitem "
}