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

From: Dmitry Gutov <[email-masked]>
Date: Sun, 22 Mar 2015 16:52:03 +0200

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.