kjh
kjh

Reputation: 3403

Dart: how many string objects are allocated when using the * operator in an assignment?

In the following code, I would expect 3 total string allocations to be made:

String str  = "abc";
String str2 = str*2; //"abcabc"

Are there fewer or more allocations made in this example? I know that strings are immutable in Dart but I'm unsure how these operations work under the hood because of this property.

Upvotes: 2

Views: 128

Answers (2)

Greg Lowe
Greg Lowe

Reputation: 16281

With optimising compilers it's difficult to know for sure. If you want to know more you can look at the generated native code with irhydra.

In general a good approach is write code to be as readable as possible, and then use tools to find the bottle necks in your code, and optimise those.

For example observatory can show you which objects are using up the most memory, and which methods are running the most.

Upvotes: 2

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657536

I have no knowledge about the inner workings of the Dart VM but I would say:

"abc" creates one String object.
String str = "abc"; makes str reference the one created String object ("abc").
str*2; creates a second String object "abcabc" which str2 refers to after the second statement.

All in all two String objects.

Upvotes: 3

Related Questions