Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoffeeScript for efficiency

Tags:

coffeescript

I have a CoffeeScript code

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

I was looking for ways how to improve speed of my code and found what it compiles into:

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 that with my own JavaScript

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

I have measured the script to be significantly faster (from 25 to 15 ms). Can I somehow force CoffeeScript to compile into code similar to mine? Or is there other solution?

Thank you.

like image 948
ondrejsl Avatar asked Aug 26 '26 06:08

ondrejsl


1 Answers

Assuming your loop will always go from a smaller number to a bigger number, you can use by 1:

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

Which compiles to:

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 possibly a bit.

like image 93
phenomnomnominal Avatar answered Aug 28 '26 14:08

phenomnomnominal