View Single Post
  #12   Spotlight this post!  
Unread 06-04-2004, 22:00
gnormhurst's Avatar
gnormhurst gnormhurst is offline
Norm Hurst
AKA: gnorm
#0381 (The Tornadoes)
Team Role: Programmer
 
Join Date: Jan 2004
Location: Trenton, NJ
Posts: 138
gnormhurst will become famous soon enoughgnormhurst will become famous soon enough
Re: Do you use ternary operators in your code?

If you're worried about speed, consider that some compilers may give faster code for one idiom over another. Once, I was working on the inner loop of a 2-D image filtering program, so there were four nested loops, which gave width x height x filterWidth x filterHeight loops per image frame, or over 3 million iterations for a 720x480 image and a 3x3 filter -- so I spent some time tweaking it for speed.

I was surprised to learn that this
Code:
  h = ( FW2 - xt );
  h = ( x+h  < 0 ) ?     -x : h; 
  h = ( x+h >= PW )? PW-x-1 : h;
was slower than this

Code:
  h = ( FW2 - xt );
  if ( x+h < 0 )
    h = -x;
  else if ( x+h >= PW )
    h = PW-x-1;
Perhaps it was faster because it only took one branch at a time, whereas the ternary method always executed both expressions. Or maybe it was faster because the compiler wasn't very good. These days speed isn't often an issue, and I haven't come close to the 26.2 ms budget. But when speed is an issue, consider this.
__________________
Trenton Tornadoes 381
2004 Philadelphia Regional Winners
2006 Xerox Creativity Award
---
My corner of the USPTO.
My favorite error message from gcc: main is usually a function
My favorite error message from Windows: There is not enough disk space available to delete this file.