AutoHotkey Speed Tips

A Collection of Techniques for Speeding Up Your AutoHotkey Scripts

I recently received the follow message from an AutoHotkey user perusing my blogs:

Jack, you can’t post false statements like this:

“However, the ternary does not provide better performance than the traditional If-Then-Else statement format.”

The ternary operator is inarguably faster than if/else and I encourage you to try this yourself.

I recently switched the core logic of my JSON parser from If/Else to ternary and saw an incredible speed increase. To the point where I only use If/If Else/Else statements when absolutely necessary (Ex: If I must have a loop in the middle of a check).

You can code entire blocks using nothing but ternary as long as you use proper parentheses, commas, and function calls.

There is a very well done AHK forum post that covers script optimizations and they report that ternary performs FORTY PERCENT FASTER than if/else statements.

Not sure if hyperlinks are allowed in these comments, so instead I’ll advise googling “AHK How to optimize the speed of a script as much as possible.” The first result should be the article in question. Pages 1 and 4 have tons of script speed gold in them.

I hope you’ll consider correcting/updating this article.

Groggy Otter

Comment on “AutoHotkey Toggles and the Ternary Operator”

I wrote that blog five years ago and I don’t know that I was talking about performance speed. I think I was referring to how the two expressions operate. In any case, I used a poor choice of words and have drawn a line through the comment.

However, Grotty Otter did inspire me to look up the post “How to optimize the speed of a script as much as possible.” The AutoHotkey Forum thread includes a treasure trove of things you can do to speed up your scripts. Since most of the recommendations deal with incrementally small differences, you will enjoy much greater improvement when you apply them to longer scripts.

After reviewing most of the techniques found in the forum thread, I surmised that the following tip sums up many of the tricks:

#1 Speed Tip Derived from a Quick Scan of the “Optimize Speed” AutoHotkey Forum Post: Combine certain types of AutoHotkey code into single lines (e.g. expressions, multiple variable assignments, ternary operators) to take advantage of Comma Performance.

You’ll find most of my scripts relatively short—therefore I rarely dig into speed tips. Yet, occasionally I encounter sluggishness which I must address.

More Script Speed Issues

The majority of the tips in the forum post linked above deal with the differences between specific command techniques. While I think they are important (especially in long scripts), I’ve found that other factors such as script structure create a much greater source of drag. Redundant loops or actions, Web site connection problems, screen rendering during updates, and other aspects of script coding often cause much more significant delays. Sometimes rewriting a script can provide the most improvement in performance speed.

Below I include a list of blogs where I address various speed issues I’ve encountered in scripts. Or, occasionally, I discover a significantly better method for improving performance through little-known AutoHotkey commands.

But first, in order to fix sluggishness problems, we need a method for measuring script/command processing times.

Timing Script Speed, February 28, 2019

Certain Types of Subroutines Tend to Eat Up Time (Loops, On-Screen Changes, Multiple Drive Accesses, etc.)—Use This Simple Timer Routine to Figure Out How to Increase AutoHotkey Script Speed

Anytime you use AutoHotkey to make iterative changes in the controls in a GUI (Graphical User Interface) pop-up window, force multiple access to hard drive files, or implement repetitious subroutines (almost always with some form of a loop), you run the risk of slowing down your script. Minor changes to your script can make a significant difference in how fast it runs—but you need to measure processing time.

Note: If the speed test discussed in the linked blog returns zeros, use QueryPerformanceCounter(), which gives more precision than A_TickCount‘s 10ms.

* * *

For all the talk about Send versus SendInput for speed, check out Control, EditPaste. The command blows everything else away!

For Speed, Replace the Send Command with Control, EditPaste,

The Control, EditPaste Command Adds Great Speed to Standard Text Insertion Routines—within Certain Limits

When I put the EditPaste, String command (found at the bottom of the Cmd, Value list on the AutoHotkey Control command page) in the CopyRef.ahk script, it blew my mind. After watching numerous character-by-character text insertions slowly dribble in, I found the immediate effect of EditPaste astonishing. I thought that I had discovered a panacea for slow substitution or insertion. Not so! While Control, EditPaste makes a dramatic improvement in the CopyRef.ahk script, its limitations prevent it from becoming a universal solution for slow text replacement.

Also found in Jack’s Motley Assortment of AutoHotkey Tips.

* * *

Waiting for Web Data to Download,

A Look at a Manufactured Looping Technique Using the Goto Command to Ensure the Download of Web Page Source Code in an AutoHotkey Script

I ran into a problem with the SynonymLookup.ahk script. On occasion, the menu would appear showing only the original bold and bulleted search term as its sole menu item. This occurred when the script finished processing before downloading the source code from the page. As often happens when working on the Internet, the Web connection took a little too long to perform its work.

Web Download Tip: From “Build Your Own Dream Thesaurus Word Replacement Tool (AutoHotkey Web Application),” I used the following function (found in the examples on the UrlDownToFile command page) rather than the UrlDownloadToFile command because it loads the Web page code directly into a variable and, unlike the UrlDownToFile command, continues to work in AutoHotkey V2.0:

  whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
  whr.Open("GET", WebPage, true)
  RefSource := whr.ResponseText
  Return RefSource

Working with variables rather than files offers tremendous speed advantages by eliminating disk accesses.

Note: Each time you click a link or refresh in a Web browser, your system attempts to connect to the address. Many people have found that re-clicking can cause the remote server to react quicker. The technique discussed in this blog simulates that action.

* * *

Next, we look at problems associated with data loading speed.

AutoHotkey Script Speed Problems (Scripting Insights),

When Debugging AutoHotkey Script Speed Problems, Look at Loops First

A number of scripting techniques can cause apps to run slow. These lags might occur when running long loops, doing extensive searches, or making numerous hard drive reads and writes. But the primary culprit tends to hide within loops or redundant operations of any type. However, you may need to look deeper to find the real source of the problem.

It seems that the number one factor for increasing load speed involved hiding the GUI window. The time for loading the test file dropped by a factor of six. By comparison, even removing the newly added Progress GUI control offers negligible improvement. However, I reached the wrong conclusion! I did not fully understand the inner workings of this supposed solution.

* * *

Sometimes after solving all the little logic problems, a script needs a major rewrite to streamline the processing.

When to Rewrite Your AutoHotkey Scripts,

AutoHotkey Scripting Philosophy or Speeding Up the InstantHotstring.ahk script

Ultimately, the experienced AutoHotkey practitioner might rewrite all (or a large section) of the code—tossing the original. This often occurs after early-on launching into one solution—then, later, once you understand the problem, regrouping and rewriting.

* * *

At the time I wrote this set of simulated Case statements, the new AutoHotkey Switch command did not exist. I’m sure that this solution runs at least 40% faster than the original If-Else alternative.

Use the Ternary Operator to Create Conditional Case Statements or Switches,

While AutoHotkey Does Not Include a Conditional Case Statement, You Can Build Your Own Using the Ternary Operator

Note, January 13, 2020: AutoHotkey now includes a Switch command with more flexibility and speed comparable to this pseudo-switch.

You can simulate any Case statement with a series of If…Else If…Else conditionals or these Ternary operators:

  Value := Var = 'R' ? 'Road'
    : Var = 'M' ? 'Mountain'
    : Var = 'T' ? 'Touring'
    : Var = 'S' ? 'Other sale items'
    :'Not for sale'

(The above represents a single line of code using line continuation techniques.)

* * *

The powers-that-be at AutoHotkey added a new Switch/Case command eliminating the need for the original ternary pseudo-switch which generated the previous discussion. I tested the speed of each and they produced numbers in the same ballpark.

A Look at the New Switch/Case Command,

In the DateStampConvert.ahk Script, Rather than Using a Series of If-Else Statements (or the Ternary Operator), the New Switch Command Sets Up Case Statements for Alternative Results—Plus, Easily Add Conversions for Spanish, German, French, and Italian Date Formats

The Switch Command offers greater flexibility than cascading ternary operators and uses simpler syntax than a series of If-Else statements. In those situations where you need to pick one out of a number of alternatives, the Switch command sets up a structure for making that selection—without losing any of the speed created by the use of the ternary operator.

Click the Follow button at the top of the sidebar on the right of this page for e-mail notification of new blogs. (If you’re reading this on a tablet or your phone, then you must scroll all the way to the end of the blog—pass any comments—to find the Follow button.)


This post was proofread by Grammarly
(Any other mistakes are all mine.)

(Full disclosure: If you sign up for a free Grammarly account, I get 20¢. I use the spelling/grammar checking service all the time, but, then again, I write a lot more than most people. I recommend Grammarly because it works and it’s free.)

Find my AutoHotkey books at ComputorEdge E-Books!

Find quick-start AutoHotkey classes at “Robotic Desktop Automation with AutoHotkey“!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s