Why does a loop go faster if you add condition in it ?

The other day I 've added a condition within a loop and I expected the code to go slower but it actually went faster !
You add a condition and the loop goes faster ... that's not logical for me and I'd like to understand it so if you have an explanation please post it below.
I've also discovered that this anomality happens only when the code is within a try-catch block.
I've reproduced the phenomenon with this little example class.
Try to comment and uncomment the only condition within the loop and to do the same for the exception. If you use the java 5 you should see similar results (haven't try with other JVM)
public class Test {
    public Test() {}
    public static void main(String[] args) {
        Test t = new Test();
        t.execute();
     * With try-catch :
     *    with condition           ms = 2641  (faster)
     *    without condition        ms = 3047 
     * Without try-catch :
     *    with condition           ms = 2625 
     *    without condition        ms = 2515  (faster)
    public void execute() {
        try {
            int c = 0;
            long t1 = System.currentTimeMillis();
            for (int i = 0; i < 1000000000; i++) {
                c++;
                if (c == 0) {
                    c--;
            System.out.println(" ms = " + (System.currentTimeMillis() - t1) + "  " + c);
        } catch (Exception e) {
            e.printStackTrace();
}

The other day I 've added a condition within a loop
and I expected the code to go slower but it actually
went faster ! The try block has absolutely nothing to do with method speed (unless of course you throw exceptions.)
Excluding that you ran one test with a condition where it was faster and one where it was slower.
And what exactly else was running on your computer when you did this? A virus checker? Scheduled tasks? Editor? IDE? Database? Services (like network stacks?) All of those take time from the cpu. And if even one of them did anything at all when your test was running then it will change the results.

Similar Messages

  • In the attached VI why does one loop coerce the data type while the other doesn't?

    In the attached VI why does one loop coerce  the data type while the other doesn't?
    Solved!
    Go to Solution.
    Attachments:
    AAA.vi ‏8 KB

    I'm guessing you created the Enum on the front panel.  If you right-click it and create an indicator, it will match the type, and be an enum.  LabVIEW represents enums as U16, but because the types aren't identical (for example, your enum has 3 values, but a U16 has 65,536 values), LabVIEW automatically coerces (or converts) the smaller (enum) representation into the larger (U16) value.

  • Why does my iphone die fast?

    Why does my iphone die fast?
    I mean it wont even last a day?

    Battery life is dependent on what you are using the phone for. First time users and users that have just gotten their phones tend to do a great deal with them. Extensive use of the Internet and other processor intensive tasks can drain the battery quickly. Also being located in a poor cellular coverage area can force the phone into constantly searching for a 3G signal and will drain battery as well. Check the Apple website for a link on battery suggestions or search here for other suggestions on how to minimize battery drainage.

  • Why does my battery drain fast? I've had my phone for a year and a half now with no problems until recently.

    Why does my battery drain fast? I've had my phone for a year and a half now with no problems until recently.

    Try to delete the mimeTypes.rdf file in the Firefox Profile Folder.
    * http://kb.mozillazine.org/mimeTypes.rdf
    * http://kb.mozillazine.org/File_types_and_download_actions#Resetting_download_actions
    You can use this button to go to the Firefox profile folder:
    *Help > Troubleshooting Information > Profile Directory: Open Containing Folder

  • Why does my battery discharg faster after downloading oS7?

    Why does my battery discharge faster after downloading on OS7?  i am using a iPhone 4S.
    thanks in advance
    Rick

    Try here >  iOS 7 Battery Life Draining Too Fast? It’s Easy to Fix

  • Why does photo information not available when you email a photo?

    Why does photo information not available when you email a photo?

    How are you mailing from iPhoto? If you have iPhoto set to mail using Mail.app, you can set what will be included, when you mail with Share > Mail:

  • Why does this loop create a 3D array instead of a 2D?

    Hi,
    This should be a relatively simple question. I am feeding a 1-D array (1 x 801) in a loop into a build array function and looping it back on itself to build the array. I am rather confused as to why this is producing a 3D array, can someone explain why?
    Thank you,
    Michael
    Attachments:
    QCM.vi ‏113 KB

    Where are you seeing the 3D array? If it is at the far right of the diagram, at the edge of the FOR loop, it is because you have the autoindexing set, which is going to make a 1D array of your 2D array data, a 3D array. As the two sub-vi's didn't come with your vi I don't know what the one with the "17" as an input does, nor what the other one does either, other than apparently produce two 1D arrays.
    Putnam
    Certified LabVIEW Developer
    Senior Test Engineer
    Currently using LV 6.1-LabVIEW 2012, RT8.5
    LabVIEW Champion

  • Why does adobe reader 11 not allow you tube videos to be viewed on my MAC?

    Adobe reader does not allow me to view you tube videos on my MAC.  Why?

    Every time I install the newest version, for whatever reason, if I want to watch a video, I get a missing plug in message.  I don't get the usual "allow or deny" message with it, it just won't allow me to view the video.  I watch a lot of art lessons on line and participate in blogs and this becomes very frustrating.  The odd thing, is that when I un-install Adobe 11, I can view the videos but, of course, then I can't download PDF files.  The weird thing is, other people in my neighborhood are having the same issue and don't know what to do about it.  I may just download an earlier version of Adobe because I didn't have this issue until I updated it some months back.  Maybe my 6 year old MAC can't handle the technology even though I am running on the latest Safari version?

  • HT1296 why does it say Can't sync you don't have enough access privilages when I try to sync my ipad

    Why does it say...Can't sync you don't have enough access privilages, when I try to sunc my ipad, i've never had this issus before?

    Sometimes it helps to delete the iPod Photo Cache folder when you get this message when trying to sync your devices with iTunes. This will explain where the iPod Photo Cache folder can be found on your computer and how you can delete it.
    iTunes: Understanding the iPod Photo Cache Folder.
    http://support.apple.com/kb/TS1314

  • HT201303 Why does it say free app and you ask for my credit card number if free

    Why does it ask for credit. Card info on a free app.

    How to Get Apps From the App Store Without a Credit Card
    http://ipadhelp.com/ipad-help/how-to-get-free-apps-from-the-app-store-without-a- credit-card/
    Creating an iTunes Store, App Store, iBookstore, and Mac App Store account without a credit card
    http://support.apple.com/kb/ht2534
    Why can’t I select None when I edit my payment information?
    http://support.apple.com/kb/ts5366
    If None is not available - On your computer launch iTunes and click “iTunes Store” in the left navigation pane. Click the “down arrow” next to your name at the top right side of the page and click “Account.” Enter your username and password and click “View Account” to log into your account information. Next to your Payment Type, click “Edit.” Select the “None” button and click “Done.” Confirm that your card has been removed by returning to the Apple account information screen. Under Payment Type, it should say that there is no credit card on file.
    iTunes Store: Changing your payment information
    http://support.apple.com/kb/HT1918
    iTunes Store Accepted Forms of Payment
    http://support.apple.com/kb/HT5552
     Cheers, Tom

  • Why does a simple table with currency not add up correctly, it is 1p out and I can't work out why?

    I have a simple accounts table and when I add the row using sum function it is always 1p out, what am I doing wrong, or what is numbers doing wrong?

    M,
    Since we can't see your situation we can't be sure what is going on. The most usual reason for unexpected sums is that there fractional parts that we can't see. This will happen on calculations, not directly entered data. So, if you have a list of calculated values and you add them up, the result of the addition of the displayed values may differ from our expectation by a small amount, maybe 1p.
    You can prevent this by using the ROUND function in each of the individual calculations that make up the list.
    If you are computing Pounds to two places, you would write:
    =ROUND(YourOriginalExpression, 2)
    Doing that eliminates any unseen value beyond the second decimal place.
    Regards,
    Jerry

  • Why does dying internal hard drive stop you booting from external hd

    Why do I need an internal hard drive if I am booting from an external drive? Doesnt make sense,
    Disk Utility warned me that the internal hard drive is failing. I have managed to change start up disks. I have an external bootable drive and even have an empty partition on it, "just in case" I need to install a brand new OS, but here I am waiting for local disks, and I cant access my back-up OS.
    Why doesnt OSX just move past the dying faulty hard drive and get to work on the bootable disk? Basically here I am supposedly doing all the right things to cover for an emergency - I may as well have no backup strategy.
    Am I missing a step, or is this how OSX works. Perhaps if you read the steps and outcomes below, you can see if there is more I need to do?
    If I press "option" at start up, it only shows the internal drive, not recognising the external bootable drive.
    fsck -f produced a looping "missing thread" message that went on for an hour or more so I stopped that.
    I tried the dvd and command-c at start up, got through to the installer window and when I selected disk utility it hung, but no spinning ball, just nothing was happening.
    The next attempt with th DVD i changed start up disk, this time it saw the external bootable drive and I thought I was in business again.
    And here I am full circle, waiting for local disks.
    Any thoughts most welcome.
    btw, does the SMART issue a warning of a failing drive because a drive is definitely unsalvagable due to a mechanical fault? or is there a chance my drive is physiclly healthy but shows as Failing because it has unbelievable directory issues that Apple tools cannot solve - but DW could?
    PB Ti 867MHz 768MB RAM   Mac OS X (10.3.9)  
    PB Ti 867MHz 768MB RAM   Mac OS X (10.3.9)  

    The Bombich forums have helped me troubleshoot the integrity of the bootable volumes on my external hard drive which I made using Carbon Copy Cloner. The clones are fine ie after I reset nvram after booting up via command-alt-o-f, the clones are now recognised when I boot up-alt. So it seems that there was nothing wrong with the bootable volumes on the external drive per se.
    However, the Powerbook will still not boot up past "Waiting for local disks".
    As it stands now, nobody seems to be able to give a reason why I cannot bypass the failed internal hard drive. I found a Knowledge base article from Apple saying Cmd-Alt-shift-delete at start-up should skip you to the next working volume hitched up to your computer, but that didn't work either.
    I have a new internal HDD coming, so prior to installing it, the final part of the troubleshoot will be to reboot the PB without an internal HDD. I will see what happens and see what conclusions can be drawn from that. Unless anyone has a clue now from what I have posted?
    PB Ti 867MHz 768MB RAM   Mac OS X (10.3.9)  

  • Why does while loop pause during operation

    Hi everyone,
    I have written the attached code which will eventually be a part of a bigger program. The program is intended to log some test value, in this case just the date and time  to a csv file  when a button is pressed (log in WHITE, loop1).  Loop2 is intended to read a test value from a line in the first csv file and then add an extra test value to the end of that line when the serial number matches and then saves that line to a new csv file. This all works well but loop2 seems to pause a few times before continuing when either of the log button is pressed. I tried putting the code in 1 while loop with no success. Can anybody see what I am doing wrong?
    Attachments:
    ResinV10_csv.vi ‏25 KB

    Maiz wrote:
    Can anybody see what I am doing wrong?
    In addition to waht has been said already, your code is extremely convoluted.
    How often does the "read" file change? Do you really need to read the entire file with thousands of rows every ms just to look at one row?. If the file never changes, you could read it once before the loop.
    The way do do array opearions is mind boggling. You take one row, Index out the first element twice in parallel (once is enough!), then you index out the first element, built it into an array of one element, and compare that array with a scalar. Would't comparing the orignal element with the scalar be equivalent?
    Index array is resizable, you only need one instance.
    Getting five elements in a row just to build them back into a 1D array seems rather pointless. If the array has only five elements, there is nothing to do, and if it has more elements, you cold use "array subset", and if it has fewer elements, use "reshape array" to size 5.
    The correct format for reading strings is %s (not %.10f).
    Since you want both loops to run at the same speed, why don't you put it all in one loop? (this even eliminates the local variable) Then you could use a parallel loop for the file saving, using queues in order not to slow down the main loop. In the parallel loop, open the files before the loop, use lowlevel writes inside the loop, and close the files once the program stops.
    Can you explain your setup and what the program is supposed to do? I am sure it could be done with 20% of the current code.
    LabVIEW Champion . Do more with less code and in less time .

  • SLOW MAC: Why does my mac run faster during the "erase free space" operation?

    Hi community!
    So I've been using my Macbook Pro Late 2012 edition for just over a year and a half now, and to no surprise, I find the spinning beachball whirling away more often than I'd care to see it. So I start a full mac clean-up including deleting login items, using Appzapper to clear up my apps, using Onyx to clear up some cache elements, deleting unused files and freeing up hard drive space.
    I've successfully cleared over 60% of disk space, (200GB used, 300GB free), but I find a recurring problem persisting, despite my best efforts to get rid of it. You see, every few seconds, the spinning beach ball appears and freezes up my entire desktop no matter what I'm doing. Trying even the simplest things, like opening the apps in the dock or right clicking a file takes ages, movies freeze up all the time, regardless of what app plays them, finder is slow and it has nothing to do with my ram usage (I use the app FreeMemory to check in real-time how much I'm using) or my CPU usage (Activity monitor open at all times). It has to be the drive.
    So then I tried running ClamXav, and found a windows trojan, which I deleted manually, but no change.
    Now, during all these stages I was regularly running erase free space opeartions (Fast x1), and noticed something curious: during the operation, my problem disappears. I still get occasional loading beach balls, and ocassional jumps in movies, but other than that, I can use my mac normally again.
    So now, I'm constantly running erase free space operations and it's painfully annoying to say the least.
    I've tried defragging, to no avail.
    I had the problem on Mountain Lion, and upgraded to Mavericks thinking that could change it (by the way it took 18 hours to install mavericks, don't know if that's related).
    In other words, I need your help. Does anybody know if I've no choice but to buy an external hardrive, backup my data, and erase my entire homedrive? Can this situation still be salvaged?
    Thanks!

    EtreCheck version: 1.9.12 (48)
    Report generated 17 Jun 2014 08:24:26 GMT+2
    Hardware Information:
              MacBook Pro (13-inch, Mid 2012) (Verified)
              MacBook Pro - model: MacBookPro9,2
              1 2.5 GHz Intel Core i5 CPU: 2 cores
              4 GB RAM
    Video Information:
              Intel HD Graphics 4000 - VRAM: (null)
                        Color LCD 1280 x 800
    System Software:
              OS X 10.9.3 (13D65) - Uptime: 1 day 0:37:38
    Disk Information:
              APPLE HDD TOSHIBA MK5065GSXF disk0 : (500,11 GB)
                        EFI (disk0s1) <not mounted>: 209,7 MB
                        Macintosh HD (disk0s2) / [Startup]: 499,25 GB (287,47 GB free)
                        Recovery HD (disk0s3) <not mounted>: 650 MB
              OPTIARC DVD RW AD-5970H 
    USB Information:
              Apple Inc. FaceTime HD Camera (Built-in)
              Apple Computer, Inc. IR Receiver
              Apple Inc. BRCM20702 Hub
                        Apple Inc. Bluetooth USB Host Controller
              Apple Inc. Apple Internal Keyboard / Trackpad
    Thunderbolt Information:
              Apple Inc. thunderbolt_bus
    Configuration files:
              /etc/hosts - Count: 15
    Gatekeeper:
              Anywhere
    Kernel Extensions:
              [loaded] com.Cycling74.driver.Soundflower (1.6.2 - SDK 10.6) Support
              [not loaded] com.anchorfree.tun (1.1.1 - SDK 10.8) Support
              [not loaded] com.iospirit.driver.RBTSRPlugin (1.18 - SDK 10.6) Support
              [loaded] com.iospirit.driver.rbiokithelper (1.21 - SDK 10.6) Support
              [loaded] com.manycamllc.driver.ManyCamDriver (0.0.9 - SDK 10.5) Support
              [not loaded] com.paceap.kext.pacesupport.leopard (5.8 - SDK 10.4) Support
              [not loaded] com.paceap.kext.pacesupport.master (5.8) Support
              [not loaded] com.paceap.kext.pacesupport.panther (5.8 - SDK 10.3) Support
              [loaded] com.paceap.kext.pacesupport.snowleopard (5.8 - SDK 10.6) Support
              [not loaded] com.paceap.kext.pacesupport.tiger (5.8 - SDK 10.4) Support
              [not loaded] com.roxio.BluRaySupport (1.1.6) Support
              [not loaded] com.roxio.TDIXController (2.0) Support
              [loaded] com.waves.driver.soundgrid (2.0.0) Support
              [loaded] net.osculator.driver.OSCulatorIOKit (2.0 - SDK 10.5) Support
              [loaded] org.virtualbox.kext.VBoxDrv (4.2.16) Support
              [not loaded] org.virtualbox.kext.VBoxNetAdp (4.2.16) Support
              [not loaded] org.virtualbox.kext.VBoxNetFlt (4.2.16) Support
              [loaded] org.virtualbox.kext.VBoxUSB (4.2.16) Support
    Startup Items:
              PACESupport: Path: /Library/StartupItems/PACESupport
    Launch Daemons:
              [loaded] com.adobe.fpsaud.plist Support
              [loaded] com.adobe.SwitchBoard.plist Support
              [loaded] com.anchorfree.ajaxserver.plist Support
              [loaded] com.google.keystone.daemon.plist Support
              [loaded] com.iospirit.candelair.daemon.plist Support
              [loaded] com.iospirit.candelair.sync.plist Support
              [loaded] com.microsoft.office.licensing.helper.plist Support
              [running] com.paceap.eden.licensed.plist Support
              [running] com.waves.daemon.SoundGridProtocolService.plist Support
              [loaded] net.sourceforge.MonolingualHelper.plist Support
              [loaded] org.macosforge.xquartz.privileged_startx.plist Support
              [loaded] PACESupport.plist Support
    Launch Agents:
              [not loaded] com.adobe.AAM.Updater-1.0.plist Support
              [loaded] com.adobe.CS5ServiceManager.plist Support
              [loaded] com.google.keystone.agent.plist Support
              [running] net.culater.SIMBL.Agent.plist Support
              [loaded] org.macosforge.xquartz.startx.plist Support
              [running] org.tigris.scplugin.launch.plist Support
    User Launch Agents:
              [loaded] com.facebook.videochat.[redacted].plist Support
              [not loaded] org.virtualbox.vboxwebsrv.plist Support
    User Login Items:
              iTunesHelper
    Internet Plug-ins:
              Flip4Mac WMV Plugin: Version: 3.0.0.126   - SDK 10.8 Support
              FlashPlayer-10.6: Version: 13.0.0.214 - SDK 10.6 Support
              Default Browser: Version: 537 - SDK 10.9
              Flash Player: Version: 13.0.0.214 - SDK 10.6 Outdated! Update
              QuickTime Plugin: Version: 7.7.3
              o1dbrowserplugin: Version: 5.4.2.18903 Support
              zako: Version: zako 1.0.0.0 - SDK 10.8 Support
              SharePointBrowserPlugin: Version: 14.0.0 Support
              googletalkbrowserplugin: Version: 5.4.2.18903 Support
              Silverlight: Version: 5.1.10411.0 - SDK 10.6 Support
              JavaAppletPlugin: Version: Java 7 Update 21 Check version
    Safari Extensions:
              ChatZum: Version: 1.31
              AdBlock: Version: 2.6.0
    Audio Plug-ins:
              BluetoothAudioPlugIn: Version: 1.0 - SDK 10.9
              AirPlay: Version: 2.0 - SDK 10.9
              AppleAVBAudio: Version: 203.2 - SDK 10.9
              iSightAudio: Version: 7.7.3 - SDK 10.9
    iTunes Plug-ins:
              Kaleidostrobe: Version: 1.0.0 ©2002 Shehryar Lasi
              Quartz Composer Visualizer: Version: 1.4 - SDK 10.9
    User Internet Plug-ins:
              BlueStacks Install Detector: Version: Unknown
              Google Earth Web Plug-in: Version: 7.1 Support
    3rd Party Preference Panes:
              Flash Player  Support
              Flip4Mac WMV  Support
              Growl  Support
    Time Machine:
              Time Machine not configured!
    Top Processes by CPU:
                   3%          SGProtocolService
                   2%          codesign
                   2%          VLC
                   1%          coreaudiod
                   1%          CVMCompiler
    Top Processes by Memory:
              131 MB          VLC
              131 MB          com.apple.IconServicesAgent
              127 MB          Google Chrome
              111 MB          mds_stores
              60 MB          WindowServer
    Virtual Memory Information:
              1.23 GB          Free RAM
              1.15 GB          Active RAM
              913 MB          Inactive RAM
              661 MB          Wired RAM
              2.61 GB          Page-ins
              96 MB          Page-outs
    Any clues?

  • Why does my HardDrive get faster when zeroed in DiskUtility?

    Hi,
    I was having some performance issues with my MacBookPro (C2D, 2,16GHz, 2GB Ram, 120GM 5400 stock drive)
    My girlfriend has the same speced MBP so I could compare performance:
    -Mine needed 50 secs more than hers to start Adobe Photoshop CS2!!!
    -mine took 103 sec to copy a 440MB folder to the desktop (within the external drive, freshly booted system, 20GB free on HD, no USB/FW storage connceted to the computer)
    Hers took 48 sec!
    No wonder it felt dead slow! It even had trouble playing back small quicktime movies!!
    This was a big shock to me, usually a computer tends to feel slow for psycological reasons after a while but here I could compare and be sure.
    Then I did a cleaninstall incl initialising the HD before and the same folder copied in 83 secs!
    After that I zeroed it once and insallted anew: 65 sec.
    The I zeroed 7 times and insatlled another time: 50 sec.
    (just out of curiosity, I tried it again with a 7 time zeroing and it stayed at 50 sec.)
    What happens on the HD when zeroing that makes it copy the same folder quicker?
    What could be the problem of my HD?
    Would you suggest me to have it changed?
    Will this be covered by the warranty?
    Lotsa question...
    regards,
    André

    Basically, it just sounds as if your caches were full, and when you zeroed out the disc, they emptied. Why it became faster on each zeroing out, I don't know, the first one should have been the same as all the others.
    Miriam

Maybe you are looking for