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

From: Ivan Shmakov <[email-masked]>
Date: Sat, 21 Mar 2015 22:20:51 +0000

>>>>> Dmitry Gutov <[email-masked]> writes:

[…]

 > Here's the updated definition (by the way, `json-special-chars' is
 > still needed, to convert ?\n to ?n, and so on, and the performance
 > hit is negligible).

	Perhaps a plain vector may fit there?

 > (defun json-encode-string-1 (string)
 >   "Return a JSON representation of STRING."
 >   (with-temp-buffer
 >     (insert string)
 >     (goto-char (point-min))
 >     ;; Skip over ASCIIish printable characters.
 >     (while (re-search-forward "\\([\"\\/\b\f\n\r\t]\\)\\|[^ -~]" nil t)
 >       (let ((c (char-before)))
 >         (delete-region (1- (point)) (point))
 >         (if (match-beginning 1)
 >             ;; Special JSON character (\n, \r, etc.).
 >             (insert "\\" (car (rassoc c json-special-chars)))
 >           ;; Fallback: UCS code point in \uNNNN form.
 >           (insert (format "\\u%04x" c)))))
 >     (concat "\"" (buffer-string) "\"")))

	FWIW, using replace-match in the loop seem to speed up the
	routine by another few percents.

    (while (re-search-forward "\\([\"\\/\b\f\n\r\t]\\)\\|[^ -~]" nil t)
      (let ((c (char-before)))
        (replace-match
         (if (match-beginning 1)
             ;; Special JSON character (\n, \r, etc.).
             (string ?\\ (car (rassq c json-special-chars)))
           ;; Fallback: UCS code point in \uNNNN form.
           (format "\\u%04x" c))
         t t)))

[…]

-- 
FSF associate member #7257  http://boycottsystemd.org/  … 3013 B6A0 230E 334A