bug-gnu-emacs
[Top][All Lists]
Advanced

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

bug#20154: 25.0.50; json-encode-string is too slow for large strings


From: Dmitry Gutov
Subject: bug#20154: 25.0.50; json-encode-string is too slow for large strings
Date: Sun, 22 Mar 2015 16:52:03 +0200
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:36.0) Gecko/20100101 Thunderbird/36.0

Here's the version I've arrived at:

(defun json-encode-string-3 (string)
  "Return a JSON representation of STRING."
  ;; Reimplement the meat of `replace-regexp-in-string', for
  ;; performance (bug#20154).
  (let ((l (length string))
        (start 0)
        (res (list "\"")))
    ;; Skip over ASCIIish printable characters.
    (while (string-match "[\"\\/\b\f\n\r\t]\\|[^ -~]" string start)
      (let* ((mb (match-beginning 0))
             (c (aref string mb))
             (special (rassoc c json-special-chars)))
        (push (substring string start mb) res)
        (push (if special
                  ;; Special JSON character (\n, \r, etc.).
                  (string ?\\ (car special))
                ;; Fallback: UCS code point in \uNNNN form.
                (format "\\u%04x" c))
              res)
        (setq start (1+ mb))))
    (push (substring string start l) res)
    (push "\"" res)
    (apply #'concat (nreverse res))))

A bit slower than the temp-buffer version (90ms vs 80ms), but consistently faster than the current version, even on small strings. Probably the best we can do in Lisp.

If no one has any better ideas, I'm going to install it.





reply via email to

[Prev in Thread] Current Thread [Next in Thread]