Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (494)
Games in Android Showcase (114)
games submitted by our members
Games in WIP (563)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Are Ternary Operations optimized at compile time?  (Read 2008 times)
0 Members and 1 Guest are viewing this topic.
Offline Oskuro

JGO Knight


Medals: 39
Exp: 6 years


Coding in Style


« Posted 2013-07-13 21:13:08 »

Looking for smart ways to do a simple value clamp without much if/else branching, I came upon a StackOverflow thread where the same question was asked, but for C.

What surprised me in that thread was mention of ternary operations being more compiler friendly than if/else blocks.

Quote
The best rule is TELL THE COMPILER WHAT YOU WANT (ie ternary), and let it optimise for you.

Is this so in Java?

I'm asking mostly because I have a liking for ternary operations, but generally just because the code is compact, although I've been discouraged from using them in the past (at work, mostly) due to them being harder to read sometimes.

I always assumed that ternary operators where, under the hood, just a compact form of an if/else block (just like switch operations are, as far as I know).

So this code:

1  
2  
3  
4  
public static double clamp(double value, double min, double max)
{
   return value < low? low : value > high? high : value;
}


I though would be equivalent to this:

1  
2  
3  
4  
5  
6  
public static double clamp(double value, double min, double max)
{
   if(value < low) return low;
   if(value > high)return high;
   return value;
}


But now I'm suspecting that assumption is wrong. Am I wrong in my assumption that my assumption is wrong? Or was I right in my previous assumption and thus my current assumption is wrong?

(Yes, on that last line I'm being an asshole) Tongue

Offline jonjava
« Reply #1 - Posted 2013-07-13 21:23:51 »

No idea. Have to wait for one of the Java wizards to answer this one.

That being said I've never had if/else/ternary blocks being the bottleneck in my programs. I prefer if/else to ternary unless it's a really trivial thing and I can't be bothered to write a few extra lines of code.

Online Riven
« League of Dukes »

JGO Overlord


Medals: 796
Projects: 4
Exp: 16 years


Hand over your head.


« Reply #2 - Posted 2013-07-13 21:31:23 »

It compiles to (almost) the same bytecode, so the JIT can't tell the difference.

Hi, appreciate more people! Σ ♥ = ¾
Learn how to award medals... and work your way up the social rankings
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Danny02
« Reply #3 - Posted 2013-07-13 21:48:14 »

btw, switch statements are no simple if else chains. There compiled to lookup tables, because of that you are only allowed to use constants for the cases.
Online pjt33
« Reply #4 - Posted 2013-07-13 22:02:04 »

I always assumed that ternary operators where, under the hood, just a compact form of an if/else block
Indeed. You can check for yourself with the javap tool. If the class is

public class Test
{
   public static double clamp1(double value, double min, double max)
   {
      return value < min ? min : value > max ? max : value;
   }

   public static double clamp2(double value, double min, double max)
   {
      if (value < min) return min;
      if (value > max)return max;
      return value;
   }
}


then javap Test gives

Compiled from "Test.java"
public class Test extends java.lang.Object{
public Test();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>"Sad)V
   4:   return

public static double clamp1(double, double, double);
  Code:
   0:   dload_0
   1:   dload_2
   2:   dcmpg
   3:   ifge   10
   6:   dload_2
   7:   goto   23
   10:   dload_0
   11:   dload   4
   13:   dcmpl
   14:   ifle   22
   17:   dload   4
   19:   goto   23
   22:   dload_0
   23:   dreturn

public static double clamp2(double, double, double);
  Code:
   0:   dload_0
   1:   dload_2
   2:   dcmpg
   3:   ifge   8
   6:   dload_2
   7:   dreturn
   8:   dload_0
   9:   dload   4
   11:   dcmpl
   12:   ifle   18
   15:   dload   4
   17:   dreturn
   18:   dload_0
   19:   dreturn

}


As you can see, both of them are conditions, gotos, and returns. The difference is that clamp1 uses a slot on the stack to hold the value until its single dreturn, whereas clamp2 turns every return statement into a dreturn bytecode. As Riven observes, the JIT's syntax tree analysis will almost certainly reduce them to the same instructions.
Offline Oskuro

JGO Knight


Medals: 39
Exp: 6 years


Coding in Style


« Reply #5 - Posted 2013-07-13 22:15:49 »

Interesting, thanks!

Specially interesting is learning how I can analyze these things myself. Smiley

Offline Oskuro

JGO Knight


Medals: 39
Exp: 6 years


Coding in Style


« Reply #6 - Posted 2013-07-13 22:20:14 »

btw, switch statements are no simple if else chains. There compiled to lookup tables, because of that you are only allowed to use constants for the cases.

Aaaaaand that explains why they get so bitchy regarding what you use for the switch statement.

I've tried using static variables whose value is calculated at runtime, like this:
1  
2  
3  
public static int value = initValue();

public static int initValue() { return /*some operation*/; }

And it wouldn't work. Sad

Thanks!


Offline Sammidysam
« Reply #7 - Posted 2013-07-14 00:19:13 »

Do you normally not put a space before the question mark in your ternary?  If so, it would be more readable if you have a space before the question mark.  Also, parentheses would really help when you have a nested ternary operator.  People suggest always putting parentheses in when working with the ternary operator, but I'd rather just use parentheses only when I have nested ternary.  I'd suggest rewriting your clamp method as

1  
2  
3  
public static double clamp(double value, double min, double max) {
    return value < low ? low : (value > high ? high : value);
}


The opening brace on the same line just complies with the official Java coding conventions.  No big issue if you don't want it there.  Cheesy  Speaking of coding conventions, I'm writing a PDF for similar coding conventions with some changes that I'll make a topic for when I am done.
Offline Oskuro

JGO Knight


Medals: 39
Exp: 6 years


Coding in Style


« Reply #8 - Posted 2013-07-14 20:37:33 »

 Actually yes, I never add a space after the '?' in a ternary operator, visually it helps me recognize which part is the evaluation expression and which one the result.

As for parenthesis, what I often do to separate the ternary results is to linebreak and ident them.

1  
2  
3  
4  
5  
6  
public static double clamp(double value, double min, double max) 
{
    return value<low?    low
                                 : value>high?   high
                                                       : value;
}


You might also notice I put my opening braces in a newline (so my editor neatly aligns blocks vertically).

I also use coasters under drinks and favour the left side of the bed.  Stare


Readability is, like beauty, in the eye of the beholder. Trying to get stringent about code formatting is only acceptable in team environments.

Telling others how to visually format their code (when there's no actual performance hit) just makes you look like a dick.



Offline h3ckboy

JGO Coder


Medals: 5



« Reply #9 - Posted 2013-07-15 09:12:32 »

There's already a thread about open braces. Just thought I'd point that out before there's any more debate.  Grin
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Sammidysam
« Reply #10 - Posted 2013-07-15 17:03:32 »

I really didn't mean to start any debate about style at all.  I really should not have brought it up.  I didn't even bring up braces as a huge issue anyway  persecutioncomplex

Sorry about doing so.  I know now not to bring up style unless you're talking about the style necessary for a project.
Offline gimbal

JGO Knight


Medals: 25



« Reply #11 - Posted 2013-07-15 18:21:09 »

Readability is, like beauty, in the eye of the beholder. Trying to get stringent about code formatting is only acceptable in team environments.


I follow you, but when I see a novice applying MicrosoftCodeFormattingRules then I pounce without mercy.
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

Dwinin (23 views)
2014-09-12 09:08:26

Norakomi (56 views)
2014-09-10 13:57:51

TehJavaDev (69 views)
2014-09-10 06:39:09

Tekkerue (34 views)
2014-09-09 02:24:56

mitcheeb (56 views)
2014-09-08 06:06:29

BurntPizza (40 views)
2014-09-07 01:13:42

Longarmx (25 views)
2014-09-07 01:12:14

Longarmx (31 views)
2014-09-07 01:11:22

Longarmx (31 views)
2014-09-07 01:10:19

mitcheeb (38 views)
2014-09-04 23:08:59
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!