Lukasz Madon
Lukasz Madon

Reputation: 14994

optimizing redundant call on immutable objects

Consider this scala code

val word = str.toLowerCase
val chars = word.distinct.sorted

and then later

//chars.map(c => str.toLowerCase.count(_ == c))
chars.map(c => word.count(_ == c))

I created the val word to avoid creating a new lower case string for map. But, in theory, can the Scala compiler optimize it away? It knows that strings are immutable.

Upvotes: 2

Views: 133

Answers (1)

Kim Stebel
Kim Stebel

Reputation: 42047

If the compiler somehow knew that .toLowerCase always returns the same result and does not have any side effects, it could optimize several calls to .toLowerCase on the same object to just one call. However, it can't know that and in your example it's not even true. For instance, depending on the default locale used, "I".toLowerCase might be "i" or "ı". Since the default locale can change between calls, such an optimization would not be valid.

Upvotes: 7

Related Questions