does iterating over `List.asReversed()` construct ...
# getting-started
y
does iterating over
List.asReversed()
construct a copy, or is it an “efficient” operation?
s
“asReversed” uses the existing list, as a view. It’s different from “reversed”, which makes a copy.
y
cool. so is it correct to say that things that return a view don’t generally copy their elements?
s
Yes, that’s normally what is meant by a “view”. A useful convention is that function names starting with “as…” return a view, whereas function names starting with “to…” return a copy. Mostly.
👍 2
y
thanks. it’s often difficult for me to tell if an operation would create a copy, so this is a good rule of thumb to remember.
e
on immutable objects,
to…()
might not create a copy, but the difference should not be observable (unless you're comparing instances)
y
what do you mean by observable in this context? for example, I’d expect
Map<K, V>.toSortedMap()
would certainly have (some) runtime cost
e
Map
is not immutable, since
MutableMap
is a subtype
but I didn't mean performance anyway
for example,
String.toString()
doesn't return a copy, it returns the
String
instance itself. it could create a copy, but since you can't change any state in
String
, there is no observable behavior difference whether it's a copy or a view (not counting performance and not counting comparing instances with
===
)
the JVM changed
String.substring
from a view to a copy in Java 7, which changed performance and memory usage characteristics, but again, since
String
is immutable, it's not an observable difference as far as we usually care about
y
thank you for the explanation. so this is all about the behavior with regards to copying, not whether or not the implementation is expected to be performant.