我有一个CoffeeScript代码
for y in [coY - limit .. coY + limit]
for x in [coX - limit .. coX + limit]
我一直在寻找如何提高代码速度的方法,并找到了它编写的代码:
for (y = _i = _ref = coY - limit, _ref1 = coY + limit; _ref <= _ref1 ? _i <= _ref1 : _i >= _ref1; y = _ref <= _ref1 ? ++_i : --_i) {
for (x = _j = _ref2 = coX - limit, _ref3 = coX + limit; _ref2 <= _ref3 ? _j <= _ref3 : _j >= _ref3; x = _ref2 <= _ref3 ? ++_j : --_j) {
当我用自己的JavaScript替换它时
for(y = coY - limit; y <= coY + limit; y++) {
for(x = coX - limit; x <= coX + limit; x++) {
我测量的脚本要快得多(从25到15毫秒)。我可以以某种方式强制CoffeeScript编译成类似于我的代码吗?还是有其他解决方案吗?
谢谢。
答案 0 :(得分:3)
假设您的循环总是从较小的数字变为较大的数字,您可以使用by 1
:
for y in [coY - limit .. coY + limit] by 1
for x in [coX - limit .. coX + limit] by 1
编译为:
for (y = _i = _ref = coY - limit, _ref1 = coY + limit; _i <= _ref1; y = _i += 1) {
for (x = _j = _ref2 = coX - limit, _ref3 = coX + limit; _j <= _ref3; x = _j += 1) {
这不是 HEAPS 更好,但可能有点。
答案 1 :(得分:1)
我不知道哥们,编辑中的代码会为我编译:
// Generated by CoffeeScript 1.4.0
var x, y, _i, _j, _ref, _ref1, _ref2, _ref3;
for (y = _i = _ref = coY - limit, _ref1 = coY + limit; _i <= _ref1; y = _i += 1) {
for (x = _j = _ref2 = coX - limit, _ref3 = coX + limit; _j <= _ref3; x = _j += 1) {
}
}
为了让它完全像你想要的那样,你可能只需要在JavaScript中实际编写它。幸运的是,CoffeeScript具有将文字JS插入CS文件的语法。如果用反引号(`)包围JS,CS编译器会将它包含在输出中,但它不会以任何方式改变反引号中的内容。
以下是一个例子:
console.log "regular coffeescript"
#surround inline JS with backticks, like so:
`for(y = coY - limit; y <= coY + limit; y++) {
for(x = coX - limit; x <= coX + limit; x++) {
console.log('inline JS!');
}
}`
console.log "continue writing regular CS after"