7

In OOP such as C# and Java if I were to create a class to do all string manipulation, I know it is better to make all the function static. However when I need to call those functions multiple times, which one will be a better option (in the context of using less resources):

  1. Creating an object one time only and call the function using that object.

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

or

  1. Calling the class directly everytime

    StringManipulation.reverse("something");
    StringManipulation.addPadding("something");
    StringManipulation.addPeriod("something");
    
Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 5
    I'd plump for the second one since it emphasises to the reader that the function does not require an object instance. – Bathsheba Sep 30 '15 at 08:41
  • http://www.c-sharpcorner.com/uploadfile/abhikumarvatsa/static-and-non-static-methods-in-C-Sharp/ – sujith karivelil Sep 30 '15 at 08:41
  • This answer may help you: http://stackoverflow.com/questions/1496629/do-static-members-help-memory-efficiency – Trevi Awater Sep 30 '15 at 08:42
  • Since Strings are immutable, either you go via the object way or static method, a new string object will be created. Resource-wise both should be same. – blogbydev Sep 30 '15 at 08:57

3 Answers3

1

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.

Mohit S
  • 13,723
  • 6
  • 34
  • 69
1

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

Remy Grandin
  • 1,638
  • 1
  • 14
  • 34
1

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.

stinepike
  • 54,068
  • 14
  • 92
  • 112