sigget sigget -4 years ago 126
Groovy Question

Are string constants in Groovy interned like they are in Java?

I'm creating large data structures of lists and maps with strings as keys in those maps. The same keys are used over and over again thousands of times. If these strings are not interned my code will consume a lot of memory with just repetitions of the same text.

To create these structures I'm using the map literal syntax, and it's specifically the constants there I'm curious about.

[
name: "text",
children: something.collect { [name: it.name, city: it.city] }
]

Answer Source

Yes, regarding your question strings behave in groovy just the way they do in java. You can easily test this by opening a groovyConsole:

def a = "test"
def b = "test"

assert a.is(b) // asserts true

Since == is used to test object equality, you have to use is() to test if your variables reference the same object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download