Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to generally assume that toString() has a low cost?

Tags:

java

c#

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?

like image 443
James A. N. Stauffer Avatar asked Sep 17 '08 20:09

James A. N. Stauffer


People also ask

What is toString () and why we need it?

The toString method is used to return a string representation of an object. If any object is printed, the toString() method is internally invoked by the java compiler. Else, the user implemented or overridden toString() method is called.

Why should you override the toString () method?

When you create a custom class or struct, you should override the ToString method in order to provide information about your type to client code. For information about how to use format strings and other types of custom formatting with the ToString method, see Formatting Types.

What happens if there is no toString method?

If there is no implementation for toString() found in the class, then the Object class (which is a superclass) invokes toString() automatically. Hence, the Object. toString() gets called automatically.

Is toString expensive C#?

Converting an enum value to a string using the ToString() method is expensive. In general, the performance impact is negligible.


1 Answers

No it's not. Because ToString() can be overloaded by anyone, they can do whatever they like. It's a reasonable assumption that ToString() SHOULD have a low cost, but if ToString() accesses properties that do "lazy loading" of data, you might even hit a database inside your ToString().

like image 69
Scott Hanselman Avatar answered Sep 19 '22 19:09

Scott Hanselman