开发者

String class in specific languages

开发者 https://www.devze.com 2023-01-16 12:30 出处:网络
I\'m becoming more interested in API\'s and was about starting to开发者_开发知识库 write my own, but then I was thinking a bit about the standard library of Java.

I'm becoming more interested in API's and was about starting to开发者_开发知识库 write my own, but then I was thinking a bit about the standard library of Java.

The standard library of Java has a String class with tons of methods, isn't this bad design? I mean, if I would create a new instance of the String class, it would create an object with dozens of methods (toUpper, toLower, etc.); wouldn't this take up much memory for such a simple string?

Thanks,

William van Doorn


No - you only "pay" for methods once, not once per instance. After all, the code doesn't change for each different instance of String, so why would you want a new copy of it for each instance?

(In some prototype based languages I suspect there may be penalties for objects with lots of methods, depending on how they're assigned... but you'd have to ask about very specific situations.)

While the String class in Java does have a lot of methods, the same situation occurs in many platforms - because there are so many ways you can use a string.


Methods don't take up memory per object. You can think of a.myMethod() as syntactic sugar for myMethod(a). (Of course, there's more going on behind the scenes, but this might help you understand why a whole lot of methods does not mean that object creation needs a lot of memory.)


Methods don't add to objects memory space.

That is until they are called. Then some memory will be taken for the new stack frame and released back after the method is through.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号