Guest User

AHK - Ternary vs If/Else vs Switch Performance Test

a guest
Mar 6th, 2022
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. if_vs_ternary_vs_switch()
  2.  
  3. if_vs_ternary_vs_switch()
  4. {
  5.     ; Testing speed of if vs ternary vs switch
  6.     ; Iterations: 100,000,000 of 4 loops
  7.     ; Results:
  8.     ; Tern:          77.010257
  9.     ; Switch:        95.079987
  10.     ; If/else:      110.643269
  11.     iterations := 10000000
  12.     str := ""
  13.    
  14.     qpx(1)
  15.     t := 0
  16.     f := 0
  17.     Loop, % iterations
  18.     {
  19.         Loop, 4
  20.             If (A_Index = 3)
  21.                 t++
  22.             Else If (A_Index = 2)
  23.                 t++
  24.             Else If (A_Index = 1)
  25.                 t++
  26.             else f++
  27.     }
  28.     str .= "`nIf/else: " qpx()
  29.    
  30.     qpx(1)
  31.     t := 0
  32.     f := 0
  33.     Loop, % iterations
  34.     {
  35.         Loop, 4
  36.               (A_Index = 3) ? t++
  37.             : (A_Index = 2) ? t++
  38.             : (A_Index = 1) ? t++
  39.             : f++
  40.     }
  41.     str .= "`nTern: " qpx()
  42.    
  43.     qpx(1)
  44.     t := 0
  45.     f := 0
  46.     Loop, % iterations
  47.     {
  48.         Loop, 4
  49.             Switch A_Index
  50.             {
  51.                 Case 3: t++
  52.                 Case 2: t++
  53.                 Case 1: t++
  54.                 Default: f++
  55.             }
  56.     }
  57.     str .= "`nSwitch: " qpx()
  58.    
  59.    
  60.     MsgBox, % str
  61.     Return
  62. }
  63.  
  64. ; qpx(1) starts it and qpx() stops timer and returns time
  65. qpx(N=0) {  ; Wrapper for QueryPerformanceCounter() by SKAN  | CD: 06/Dec/2009
  66. Local   ; www.autohotkey.com/forum/viewtopic.php?t=52083 | LM: 10/Dec/2009
  67. Static F:="", A:="", Q:="", P:="", X:=""
  68. If (N && !P)
  69.     Return DllCall("QueryPerformanceFrequency",Int64P,F) + (X:=A:=0)
  70.          + DllCall("QueryPerformanceCounter",Int64P,P)
  71. DllCall("QueryPerformanceCounter",Int64P,Q), A:=A+Q-P, P:=Q, X:=X+1
  72. Return (N && X=N) ? (X:=X-1)<<64 : (N=0 && (R:=A/X/F)) ? (R + (A:=P:=X:=0)) : 1
  73. }
Advertisement
Add Comment
Please, Sign In to add comment