开发者

String memory allocation in java

In an Servlet class, 开发者_Python百科I am having the checks

if("Mail".equals( request.getParameter(mode)) || "Chat".equals( request.getParameter(mode))) {}

My question is about the memory allocated for the strings "Mail" and "Chat". Will it create new string objects for every request to this servlet. What about GC?.


No, it won't create a new object each time. String constants are interned - they're created once and put in a special pool.

Not only will it not create a new string each time you run the code, but if you use the constants "Mail" or "Chat" elsewhere in your code, they'll use the same string objects too.

From the Java Language Specification section 3.10.5:

Each string literal is a reference (§4.3) to an instance (§4.3.1, §12.5) of class String (§4.3.3). String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions (§15.28)-are "interned" so as to share unique instances, using the method String.intern.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜