Created
          June 7, 2025 20:13 
        
      - 
      
 - 
        
Save talbergs/4541935c07369dcc35f158924792da0f to your computer and use it in GitHub Desktop.  
    Swap variables XOR
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | <?php | |
| // Swap these two variables. | |
| $a = 13; | |
| $b = 72; | |
| print_r(compact('a', 'b')); | |
| // Now swap in a "memory efficient" way. | |
| $a ^= $b; | |
| $b ^= $a; | |
| $a ^= $b; | |
| print_r(compact('a', 'b')); | |
| // Now swap again using array. | |
| [$a, $b] = [$b, $a]; | |
| print_r(compact('a', 'b')); | |
| // Now swap using temporary variable. | |
| $tmp = $b; | |
| $b = $a; | |
| $a = $tmp; | |
| print_r(compact('a', 'b')); | |
| $j = 500000000; | |
| // Benchmark method 1. | |
| $a = 13; | |
| $b = 72; | |
| memory_reset_peak_usage(); | |
| $sec_init = time(); | |
| $i = $j; | |
| while (--$i) { | |
| $a ^= $b; | |
| $b ^= $a; | |
| $a ^= $b; | |
| } | |
| printf("Mem: %s, Time: %s, Method xor\n", memory_get_peak_usage(), time()-$sec_init); | |
| // Benchmark method 2. | |
| $a = 13; | |
| $b = 72; | |
| memory_reset_peak_usage(); | |
| $sec_init = time(); | |
| $i = $j; | |
| while (--$i) { | |
| [$a, $b] = [$b, $a]; | |
| } | |
| printf("Mem: %s, Time: %s, Method des\n", memory_get_peak_usage(), time()-$sec_init); | |
| // Benchmark method 3. | |
| $a = 13; | |
| $b = 72; | |
| memory_reset_peak_usage(); | |
| $sec_init = time(); | |
| $i = $j; | |
| while (--$i) { | |
| $tmp = $b; | |
| $b = $a; | |
| $a = $tmp; | |
| } | |
| printf("Mem: %s, Time: %s, Method tmp\n", memory_get_peak_usage(), time()-$sec_init); | |
| // Mem: 419408, Time: 10, Method xor | |
| // Mem: 419624, Time: 24, Method des | |
| // Mem: 419408, Time: 6, Method tmp | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment