Better way to call Function multiple times

This question already has an answer here:

  • Performance of static methods vs instance methods 3 answers

  • the performance differences of the give two options is negligible. but the main difference is in the usage of the methods.

    if you need a method to do any general tasks independant of class objects then you will consider static methods in your design. else for object dependant tasks you should consider the instance methods.


    You should create an object if you need some initialisation, like maybe getting values or parameters from a datasource.

    The static is the way to go in your exemple as they are atomic function which return always the same result, whatever the context (stateless)

    However, in C# (I don't know in java), there is a better way : Extention methods. Basicly, you will add method to the string object which will allow to call them directly on the string object, and, if yor return object is also a string, chain them if you need to :

    public static string reverse(this string str)
    {
        // Code to reverse your string
        return result;
    }
    
    .........
    
    "something".reverse().addPadding()
    

    For more info : https://msdn.microsoft.com/en-us/library/bb383977.aspx


    I believe this will be efficient

    StringManipulation sm = new StringManipulation(); 
    sm.reverse("something").addPadding("something").addPeriod("something");
    

    Creating one instance which will get it worked.

    链接地址: http://www.djcxy.com/p/29448.html

    上一篇: 如何在使用Ember.PromiseProxyMixin时冒出被拒绝的承诺

    下一篇: 更好的方式多次调用函数