On 03 Jul 2004 12:14, "Chua Wen Ching" wrote:
Hi all,
This is an amazing post. I just want to ask.
Ternary VS IF statements.. which one improves performance?
For readability, I think if will wins the war. But can you all share your
comments.
Thanks.
(Note that any attempt to meaningfully benchmark performance needs far
more effort than this.)
I ran the following under Debug mode:
DateTime start = DateTime.Now;
string result;
for (int i = 0; i < 100000000; i++) {
if (A()) {
if (B()) {
result = "AB";
} else {
result = "A-B";
}
} else {
if (B()) {
result = "-AB";
} else {
result = "-A-B";
}
}
}
DateTime endIf = DateTime.Now;
for (int i = 0; i < 100000000; i++) {
result = (A() ? (B() ? "AB" : "A-B") : (B() ? "-AB" : "-A-B"));
}
DateTime endTern = DateTime.Now;
TimeSpan tsIf = endIf - start;
TimeSpan tsTern = endTern - endIf;
Console.WriteLine("If: {0}", tsIf.TotalMilliseconds);
Console.WriteLine("Ternary: {0}", tsTern.TotalMilliseconds);
The output was:
A True, B True: If: 2859.375 Ternary: 2484.375
Difference ~ .3 seconds
A True, B False If: 2796.875 Ternary: 2437.5
Difference ~ .36
A False, B True If: 2765.625 Ternary: 2312.5
Difference ~ .45
A False, B False If: 2578.125 Ternary: 2453.125
Difference ~ .12
In other words, over 100,000,000 repititions there was far less than .5
secs difference. I don't see how this is going to make any difference to
any program you might consider writing with .NET.
It *is* interesting that the least difference (by a long way) is when
they're both false,
Readability is in the eye of the beholder, but I know which one my eye's
on :)
--
Simon Smith
simon dot s at ghytred dot com
www.ghytred.com/NewsLook - NNTP Client for Outlook