Do you generally assume that toString() on any given object has a low cost (i.e. for logging)? I do. Is that assumption valid? If it has a high cost should that normally be changed? What are valid reasons to make a toString() method with a high cost? The only time that I get concerned about toString costs is when I know that it is on some sort of collection with many members. From: http://jamesjava.blogspot.com/2007/08/tostring-cost.html
Update: Another way to put it is: Do you usually look into the cost of calling toString on any given class before calling it?
The Java standard library seems to have been written with the intent of keeping the cost of toString calls very low. For example, Java arrays and collections have toString methods which do not iterate over their contents; to get a good string representation of these objects you must use either
Arrays.toStringorCollections.toStringfrom thejava.utilpackage.Similarly, even objects with expensive equals methods have inexpensive toString calls. For example, the
java.net.URLclass has an equals method which makes use of an internet connection to determine whether two URLs are truly equal, but it still has a simple and constant-time toString method.So yes, inexpensive toString calls are the norm, and unless you use some weird third-party package which breaks with the convention, you shouldn’t worry about these taking a long time.
Of course, you shouldn’t really worry about performance until you find yourself in a situation where your program is taking too long, and even then you should use a profiler to figure out what’s taking so longer rather than worrying about this sort of thing ahead of time.