[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

integer-to-string, fast



I applied the write-integer-to-stream to fill-pointer array. If you reserve
a global buffer for conversion it takes only 58 bytes memory, and converts quite
fast.

(defvar *itos-string-buf* (make-array 16 :element-type 'character :fill-pointer 0))

(defun integer-to-string (integer)
    (setf (fill-pointer *itos-string-buf*) 0)
    (when (minusp integer)
      (vector-push #\- *itos-string-buf*)
      (setq integer (- integer)))
    (labels ((*fast-print-number (number)
               (multiple-value-bind
                 (rest current)
                 (floor number 10)
                 (unless (zerop rest)
                   (*fast-print-number rest))
                 (vector-push
                  (svref  #(#\0 #\1  #\2  #\3  #\4  #\5  #\6  #\7  #\8 #\9) current)
                  *itos-string-buf*))))
      (declare (dynamic-extent #'*fast-print-number))
      (*fast-print-number integer))
    *itos-string-buf*)

(time (dotimes (i 1000) (integer-to-string 123)))

(dotimes (i 1000) (integer-to-string 123)) took 168 milliseconds (0.168 seconds) to run.

Peter