Results 1 to 20 of 20
  1. #1
    Dan0100 is offline Member
    Join Date
    Aug 2010
    Posts
    18
    Rep Power
    0

    Default Which is faster?

    Hey guys,
    I have a function called 1000s of times per second. It doesn't matter to me which is used but which is faster to process?
    Java Code:
    if(doPing){
      doPing=false;
    }
    
    -or-
    
    doPing = false;
    also which of these two are faster?
    Java Code:
    a = b = c = false;
    
    - or -
    
    a = false;
    b = false;
    c = false;
    Thanks for your knowledge :),
    Dan

  2. #2
    travishein's Avatar
    travishein is offline Senior Member
    Join Date
    Sep 2009
    Location
    Canada
    Posts
    684
    Rep Power
    5

    Default

    i would say the first one, in the case when doping was true would require 2 operations, and more bytes of bytecode in the java file to conditionally test, and then assign the variable, and only 1 operation if it was false. where as always assigning it would always be one operation.

    the second set, i would imagine would be the same number of operations, internally the syntax is expanded to individual assignments anyway.

  3. #3
    Eranga's Avatar
    Eranga is offline Moderator
    Join Date
    Jul 2007
    Location
    Colombo, Sri Lanka
    Posts
    11,372
    Blog Entries
    1
    Rep Power
    19

    Default

    Quote Originally Posted by travishein View Post
    i would say the first one, in the case when doping was true would require 2 operations, and more bytes of bytecode in the java file to conditionally test, and then assign the variable, and only 1 operation if it was false. where as always assigning it would always be one operation.

    the second set, i would imagine would be the same number of operations, internally the syntax is expanded to individual assignments anyway.
    Yes it is. If OP could write a small test case for this, he can observe it clearly.

  4. #4
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    Quote Originally Posted by Dan0100 View Post
    Hey guys,
    I have a function called 1000s of times per second. It doesn't matter to me which is used but which is faster to process?
    Java Code:
    if(doPing){
      doPing=false;
    }
    
    -or-
    
    doPing = false;
    also which of these two are faster?
    Java Code:
    a = b = c = false;
    
    - or -
    
    a = false;
    b = false;
    c = false;
    Thanks for your knowledge :),
    Dan
    When in doubt, try it out! Put together a piece of each code and run it thousands of time in a second, and see how well it performs against the other one.

  5. #5
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default

    Or, don't actually worry about premature optimisation.
    Write what is clear.

    I mean, this is a classic example of premature optimisation...

  6. #6
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,309
    Blog Entries
    7
    Rep Power
    20

    Default

    Let TT and TF the time it takes if a condition is true or false respectively; let AF be the time it takes to set a variable to false. If a test succeeds the entire operation takes TT+AF; if the test fails it takes TF units of time. The probability for truth/falsehood is 0.5 so on average the first code snippet takes 0.5*(TT+AF+TF) while the second snippet takes AF always. Depending on the time units taken for TT or TF you can conclude whether or not AF < TT+TF.

    The second example takes three iconst_x instructions and three istore_x instructions; the compound assignment takes one iconst_x instruction, two dup instructions and three istore_x instructions. I really don't know which one is faster; especially not when the entire thing is JIT compiled to real machine code. I do know that each variant will take just a few cycles so there is no need to worry about anything ;-)

    kind regards,

    Jos

  7. #7
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    Quote Originally Posted by Tolls View Post
    Or, don't actually worry about premature optimisation.
    Write what is clear.

    I mean, this is a classic example of premature optimisation...
    Wanting to write effective and efficient code is better than having to back and change it all later cause you realize just how slow what you wrote actually is.

  8. #8
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,309
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by Zack View Post
    Wanting to write effective and efficient code is better than having to back and change it all later cause you realize just how slow what you wrote actually is.
    Read Martin Fowler's "Factorisations"

    kind regards,

    Jos

  9. #9
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default

    Exactly.
    Spending time battling minutiae like this takes time away from the actual bottle necks of disk access, networking, and database calls. And often results in code that is harder to maintain.

    Write it clearly the first time then it's a lot easier to identify and fix the performance issues later on...and believe me, those performance issues are never caused by stuff like that in the OP.

  10. #10
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    Quote Originally Posted by JosAH View Post
    Read Martin Fowler's "Factorisations"

    kind regards,

    Jos
    I do agree that factorizing code is very important. Improving an existing function is a great idea. Being a writer, I know that going back to revise old stuff is how you make it just right.

    But let's say you write a function like this:
    Java Code:
    public double someFunc() {
        double a = 100000.0;
        int b = 2;
        int c = 12; // This used to have a purpose, but it was removed. We didn't bother to remove the allocation because, well, we're not optimizing at all.
        
        for (int i = 0; i < 5000; i++) {
            a /= (double)b;
        }
        // We didn't bother to remove the above loop when we decided to redefine a, because we're not optimizing.
        a = 1000.0;
        
        a = a / 500.0 * 500.0 + 2.0 / 2.0 + (double)b; // This is a formula we copied from somewhere, but it's not simplified to "a = a + b + 1;".
    
        return a;
    }

    This can go on and on. You can see here that this function is probably the biggest piece of garbage I've ever written, but the point still stands that without a mind for optimizing as you go, you're going to end up with hundreds of these horrendous functions.

    Before Java, I was working a lot with C++, particularly modding a game called Renegade. The game engine is fairly old (it was designed in 2002, but was never totally finished nor optimized), so every bit of code put in has to be well-optimized to improve engine performance. I actually used Assembly to hook dozens of the functions in the engine to rewrite them entirely.

    This entire situation could have been avoided if the programmers had half a mind to adopt an optimize-as-they-went school of thought. Horrendous loops that looped twice as long as necessary--particularly in those executing each frame--were a huge drag in the main code.

    Can you see where I'm coming from? I agree that you should refactor code before it's published, but it should always be optimized as you go along.

  11. #11
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default

    I take it you missed the bit about writing clearly.

    That code has nothing to do with optimising or not...that's to do with appallingly written code.

  12. #12
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    I fail to see how the points aren't related. Did you read the second half of my post, about the Renegade C++ engine?

    Badly optimized code can slow everything down if there's enough of it. Even with a few simple poor allocations (particularly in languages that aren't memory-managed, unlike Java), a program can be bogged down and can even display memory leaks that are completely undesirable to the end user.

  13. #13
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default

    We're not talking to-the-metal coding here.
    We're talking Java.

    In Java writing clear code is far more important. Yes, you can also write bollocks code, but that is almost always not clear.

    And, in your case above, writing code that was optimised for that task makes sense. In Java figuring out whether "a = b = c = false;" is faster than individual assignments is nonsense...

  14. #14
    Zack's Avatar
    Zack is offline Senior Member
    Join Date
    Jun 2010
    Location
    Destiny Islands
    Posts
    692
    Rep Power
    5

    Default

    Perhaps this particular case is a bit absurd in the grand scheme of things. But it's ridiculous to say that we should simply write code that people can understand without thinking of the consequences of writing such a code (in optimization or otherwise).

  15. #15
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,755
    Rep Power
    19

    Default

    In order to write understandable code it should be nice and modular, with nice short methods, all that malarkey (good naming etc etc). Why? Because for most of that codes life most of the cost it will incur is development and maintenance. This will far outshine any hardware costs, for all except the big data warehouses.

    Now, in order to do the writing you do need to have a certain level of understanding of how Java works, but beyond that? Yes, stick to writing it nicely.

    I have encountered too many places where they thought they had written lovely optimised stuff that might have saved them a clock tick here or there (and with Java that's almost impossible to do without second guessing the compiler), but it was nigh on unmaintainable, and rapidly became a big lump of mud...that was far from fast.

  16. #16
    j2me64's Avatar
    j2me64 is offline Senior Member
    Join Date
    Sep 2009
    Location
    Zurich, Switzerland
    Posts
    962
    Rep Power
    5

    Default

    Quote Originally Posted by Tolls View Post
    In Java figuring out whether "a = b = c = false;" is faster

    i was not so sure about your statement above, so i measured the assignments with the following code

    Java Code:
    public class Speedtest {
        public static void main(String[] args) {
            boolean doPing = true;
            boolean a, b, c;
    
            long start = 0;
    
            try {
                // starting measure multiple assignments
                start = System.nanoTime();
                a = false;
                b = false;
                c = false;
                System.out.println("single a = false in nano: "
                        + (System.nanoTime() - start));
                // starting measure one assignment
                start = System.nanoTime();
                a = b = c = false;
                System.out.println("a = b = c = false in nano: "
                        + (System.nanoTime() - start));
    
            } catch (Exception ex) {
            }
        }
    }

    your statement is true but the time difference is very small. on my machine (currently also sending mails) i got

    single a = false in nano: 5028
    a = b = c = false in nano: 4749

  17. #17
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,309
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by j2me64 View Post
    i was not so sure about your statement above, so i measured the assignments with the following code [snip]
    Timing elementary things only once fails to be relevant: the nano times might be too inaccurate to show relevant differences and the JIT compiler might have hit halfway, greatly disturbing your figures. At least try to test it a million times and take the average. Also beware that the JIT compiler is an optimizing compiler, i.e. the entire thing might be optimized away.

    kind regards,

    Jos

  18. #18
    Dan0100 is offline Member
    Join Date
    Aug 2010
    Posts
    18
    Rep Power
    0

    Default

    This has turned into a really interesting post.

    The argument of readability vs optimization, is a long debate with no clear answers.. but I think usually they go hand-in-hand; if it is readable it will mostly be optimized.

    In this situation however, I know it is a minute small question, but it informs the rest of one's knowledge. At the moment I am doing java for personal use, I have no deadlines, I am simply learning it and trying to make my programs as good as I can.

    Some situations will require the "get stuff done" mentality.
    Others will require the "get stuff done better" mentality.
    You need to chose the correct one for the job ;)

  19. #19
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    I agree with Tolls optimizing for the sake of it is a waste of time. I reckon 10% of code gets bottlenecked and it usaully the usual suspects. Complex functions etc for the sake of speed early on just adds to the complexity for code review and update.

  20. #20
    dinosoep is offline Senior Member
    Join Date
    Nov 2009
    Posts
    150
    Rep Power
    5

    Default

    I don't really care about optimazation but when I am in the need of a very eficient piece of code I use asm for the jvm. I think thats as optimized as you can get.

Similar Threads

  1. How to make my download class faster
    By pietertje in forum New To Java
    Replies: 3
    Last Post: 08-07-2010, 11:19 AM
  2. Replies: 2
    Last Post: 10-06-2008, 08:20 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •