CoffeeScript for efficiency

I have CoffeeScript code

for y in [coY - limit .. coY + limit]
    for x in [coX - limit .. coX + limit]

      

I was looking for ways to improve the speed of my code and found that it compiles:

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) {

      

When I replaced this with my own JavaScript

for(y = coY - limit; y <= coY + limit; y++) {
    for(x = coX - limit; x <= coX + limit; x++) {

      

I measured the script significantly faster (25 to 15ms). Can I somehow get CoffeeScript to compile to code similar to mine? Or is there another solution?

Thank.

+3


source to share


2 answers


Assuming your loop will always go from lower to higher, you can use by 1

:

for y in [coY - limit .. coY + limit] by 1
    for x in [coX - limit .. coX + limit] by 1

      

What compiles:



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) {

      

It's not HEAPS better, but maybe not much.

+3


source


I don't know, the code in your edit compiles for me:

// 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) {
  }
}

      

To get it exactly the way you want it, you just need to write it in JavaScript. Fortunately, CoffeeScript has a syntax for inserting literal JS into a CS file. If you surround the JS with backward inference (`), the CS compiler will include it in the output, but it won't change what it does in reverse.



Here's an example:

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"

      

Source: http://coffeescript.org/#embedded

+1


source







All Articles