gpt4 book ai didi

string - 字符串处理中Lisp性能优化方案

转载 作者:太空宇宙 更新时间:2023-11-03 18:44:33 24 4
gpt4 key购买 nike

我有一个用下划线分隔单词的字符串(例如 aaa_bbb_ccc)

我创建了一个函数来将字符串转换为驼峰命名法(例如 aaaBbbCcc)。

我想知道是否有一些我做错的事情影响了性能。这是代码:

(defun underscore-to-camel (input)
(defparameter input-clean-capitalized (remove #\_ (string-capitalize input)))
(setf (aref input-clean-capitalized 0) (aref (string-downcase (aref input-clean-capitalized 0)) 0))
input-clean-capitalized)

我还创建了第二个变体,但速度慢了约 25%(使用 time 测量了 300 万次执行):

(defun underscore-to-camel-v2 (input)
(defparameter input-clean-capitalized (remove #\_ (string-capitalize input)))
(concatenate
'string
(string-downcase (aref input-clean-capitalized 0))
(subseq input-clean-capitalized 1)))

最佳答案

首先,defparameter 不是您想要使用的。你真的应该重构你的代码是这样的:

(defun underscore-to-camel (input)
(let ((input-clean-capitalized (remove #\_ (string-capitalize input))))
(setf (aref input-clean-capitalized 0)
(aref (string-downcase (aref input-clean-capitalized 0)) 0))
input-clean-capitalized))

第二:你可以这样处理问题:

(defun underscore-to-camel-eff (input)
(declare (optimize (debug 1) (speed 3) (safety 1)))
(loop :with length = (length input)
:with i = 0
:while (< i length)
:for c = (aref input i)
:if (or (= i (- length 1))
(char/= c #\_))
:collect (prog1 c (incf i)) :into result
:else
:collect (prog1
(char-upcase (aref input (+ i 1)))
(incf i 2))
:into result
:finally (return (concatenate 'string result))))

在装有 SBCL 的我的 PC 上,它的运行时间是你的解决方案的一半。

这是一个使用正则表达式的解决方案,尽管比任何其他解决方案都慢:

(defun underscore-to-camel-ppcre (input)
(declare (optimize (debug 1) (speed 3) (safety 1)))
(ppcre:regex-replace-all "_([a-z])"
input
(lambda (target-string
start
end
match-start
match-end
reg-starts
reg-ends)
(declare (ignore start
end
match-end
reg-starts
reg-ends))
(string
(char-upcase
(aref target-string (+ 1 match-start)))))))

必要的包称为“ppcre”。您可以通过以下方式安装它

(ql:quickload "cl-ppcre")

一旦你去了http://www.quicklisp.org/beta/并安装了 quicklisp。

关于string - 字符串处理中Lisp性能优化方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18034609/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com