views:

571

answers:

6

I found this in some production login code I was looking at recently...

HttpContext.Current.Trace.Write(query + ": " + username + ", " + password));

...where query is a short SQL query to grab matching users. Does this have any sort of performance impact? I assume its very small.

Also, what is the purpose of this exact type of trace, using the HTTP Context? Where does this data get traced to? Thanks in advance!

+7  A: 

Yes it will have a performance impact whenever the TRACE conditional compilation constant is defined during build. Doing anything has some type of impact :)

As to whether or not this has a significant impact on an application. It's highly unlikely that it would as Trace is designed to be run and is run in many production applications. Only an abuse of the feature should lead to a noticable performance difference.

But as always, don't trust me, trust the profiler.

JaredPar
So do tracing calls have no impact when tracing is disabled on the page or in the web.config? Do they get "optimized out" when the page is compiled on the fly?
SkippyFire
+1  A: 

Trace messages can go to a lot of different places. You can add (or remove) TraceListeners for the Console, VisualStudio debug Window, Files, or the Event Log to name a few. You can even build your own.

Also, you can configure Trace to not do anything when compiled for Release.

Joel Coehoorn
+2  A: 

The most performance loss in this piece of code is not in the trace, but in the string concatenation through the use of the + operator. This does some inefficient memory operations that can beat an IO operation in terms of performance. I'd change it to use something like string.Concat or the StringBuilder class (or string.Format for that matter).

Jonathan van de Veen
+1  A: 

And if trace is writing to a text file it will cost more than writing to console IMHO

erdogany
Depends. If the file is buffered and only flushes when the buffer is full, on average you actually take less time. Writing to a GUI console is pretty expensive, what with font rendering, anti-aliasing, viewport clipping, etc.
TMN
In fact I thought about cost of writing to console, and thought it would be less costly, but if you say so, thats right...
erdogany
+4  A: 

I don't have the reputation points for comments yet but I wanted to make a quick statement about Jonathan's answer. The numbers I have seen seem to show that it doesn't make sense to use stringbuilder for just a handful of string concatenations. The overhead of creating the stringbuilder object outweighs the concatenation speed benefit.

William Edmondson
A: 

I guess Trace Source looks at its switch's TraceLevel before forwarding messages to the listeners. So if we keep the switch's default TraceLevel value to "Error", then tracing overhead would be greatly reduced as only "Error" traces would be sent to listeners.

just a guess...i haven't measured anything yet. Will update if I do.

mishal153