Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 5 of 5
  1. #1
    Regular Coder
    Join Date
    Jan 2005
    Posts
    470
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Speed of Switch vs If Else

    I have read that "switch" statements are faster in JavaScript than "if, else if" statements. Does the same hold true in general for PHP?

  • #2
    Senior Coder missing-score's Avatar
    Join Date
    Jan 2003
    Location
    UK
    Posts
    2,194
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I would imagine so... becuase with a switch, PHP compares an original value to a set of case values, the same holds with javascript... With an if else statement, it is given possibly different options each time and needs to do more parsing.

    The differences here are going to literally un-noticable, and for general use, dont try and convert your if else statements to switch's unless a switch() loop is a more appropriate loop to use.

  • #3
    Regular Coder
    Join Date
    Jan 2005
    Posts
    470
    Thanks
    3
    Thanked 0 Times in 0 Posts
    On basic comparisons it doesn't seem to make any difference between the two.

    http://www.php.lt/benchmark/phpbench.php

  • #4
    Senior Coder missing-score's Avatar
    Join Date
    Jan 2003
    Location
    UK
    Posts
    2,194
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Calling an if/else and switch statement 1000 times isnt anywhere near enough to get a good idea of speed difference... You would want to call it 1,000,000 - 100,000,000 times and check speed differences then, which would give a much better idea. I might try this out later actually.

  • #5
    New Coder
    Join Date
    Jul 2007
    Posts
    26
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by bauhsoj View Post
    On basic comparisons it doesn't seem to make any difference between the two.

    http://www.php.lt/benchmark/phpbench.php
    Very interesting, thanks!
    -


  •  

    Posting Permissions

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