Optimal CPU usage - findInRange or lookForAtArea



  • When attempting to identify something around a specific position (range 1), eg looking for energy near a creep.

    Is it better to use findInRange with range 1 or lookForAtArea from the perspective of CPU usage?

    Does findInRange make a subsequent call to room.find?



  • I think first thing to do would be check if it's a problem at all, you can do that with a profiler: https://github.com/gdborton/screeps-profiler/ , premature optimization and optimization without profiling are not good most of the time.

    Also the profiler can profile specified function if you pass functionFilter to it, so you can profile both variants with simple for i in range something test loop (and you will probably have to enable profiler only at the end of the main loop and do test for loop after that, so game functions monkey-patched only for testing for loop).

    And also for most public game functions you can look at their code by inserting function name in console and pressing enter, it is not always helpful but in case of RoomPosition.prototype.findInRange you can see in code that it does call room.find

     

    function (type, range, opts) {
    var room = register.rooms[this.roomName];

    if (!room) {
    throw new Error(`Could not access room ${ this.roomName }`);
    }

    opts = _.clone(opts || {});

    var objects = [],
    result = [];

    if (_.isNumber(type)) {
    objects = room.find(type, opts);
    }
    if (_.isArray(type)) {
    objects = opts.filter ? _.filter(type, opts.filter) : type;
    }

    objects.forEach(i => {
    if (this.inRangeTo(i, range)) {
    result.push(i);
    }
    });

    return result;
    }

     


  • Hi rndr,

     

    The advice is much appreciated. I brought this topic up specifically because I am using the profiler to identify areas requiring improvement.

    I hadn't though about simply looking at the function code itself. That's an excellent point. I will delve deeper into the code now to get a better handle on where I can save some time.

    Kind regards,
    Radu



  • And i just realized that simplest way to look at the code is to look at the prototype, and not trying to find instance

    RoomPosition.prototype.findInRange