Best performance practice while using modules



  • There is a question about what the best performance practice to use modules.

    In the case we use module to determine creep's role behavior, for example, which variant will be more CPU-effective:

    Module as function (from documentation):

    /// harvester.js
    module.exports = function(creep) {
        /// Some private vars
        /// Some supporting functions
        return {
            work : function() { /* JOB */ }
        }
    }
    
    /// main.js
    var harvester = require('harvester');
    for(var i in Game.creeps) {
        harvester(Game.creeps[i]).work();
    }
    

    ... or module as a result of function call:

    /// harvester.js
    module.exports = (function() {
        /// Some private vars
        /// Some supporting functions
        return {
            work : function(creep) { /* JOB */ }
        }
    }());
    
    /// main.js
    var harvester = require('harvester');
    for(var i in Game.creeps) {
        harvester.work(Game.creeps[i]);
    }
    

    ... or any other way?

    Have anybody thought about this and mb did any cpu-usage measures?


  • SUN

    In terms of "CPU performance": each require call takes 0.6 cpu on the average, no matter how you use it's result further.
    (that is according to my own measures)

    So, if you're interested in a high performance, you may think about minimising the number of modules (the number of require calls in your script) rather then it's further usage.

    About your initial question: I don't see any evident difference in it (due to measures I did), but there may be other opinions.



  • Хорошо, спасибо.

    P.S. Увидел в соседней ветке подробную расписку по замерам 🙂



  • Interesting, so there is a direct relationship between maintainability and cost (assuming code is more maintainable when divided into modules). For you to decide if its worth it! 



  • I've found that each require call takes an amount of time correlated to how much the file contains...  Following neomatrix's testing I created a bundle containing all my code then measured it's require time in main.js... 23 ms.