Sudhir Srinivasan wrote:
Given that this process seems to be slightly complicated, is there a more simpler / efficient way of performing arithmetic operations on strings? Would StringBuilder class be appropriate for such string manipulation??
How do you know that a StringBuilder requires less memory than a String?Gaurangkumar Khalasi wrote: . . . YES, StringBuilder is better than String for manipulation... requiring less memory space!!!
Campbell Ritchie wrote:How do you know that a StringBuilder requires less memory than a String?
Campbell Ritchie wrote:You do not choose operations because of their “efficiency” or their memory footprint, but because of their functionality.
No, you are creating one object there, since "Hello" and " How are you?" already exist.Gaurangkumar Khalasi wrote: . . . So, we require to create 3 objects and ofcourse "Hello" will be eligible for garbage collection... . . .
Campbell Ritchie wrote:I can identify at least six objects in the following code
Campbell Ritchie wrote:Why don’t you use a Scanner and its nextInt() method?
Campbell Ritchie wrote:
How do you know that a StringBuilder requires less memory than a String?
You do not choose operations because of their “efficiency” or their memory footprint, but because of their functionality.
Yes, you use StringBuilder because you need mutable counterparts to String, and that is its functionality. It adds faster execution to that
functionality. We are lucky here.
Campbell Ritchie wrote:A StringBuilder defaults to a capacity of 16, unless you specify otherwise to its constructor. You pass "Hello" (5 characters) and append " How are you?" (13 characters), so what will its capacity increase to? Are you sure you are using less memory?
Campbell Ritchie wrote:So you see that use of memory can be much more complicated than you think.
But who cares; I can go and take my wife, daughters, sons-in-law and grandsons for dinner and it will cost £xxx. For the same money, I can buy a hard drive with 2TB of capacity. And we are worrying about a few dozen bytes!
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |