Condensing Autohotkey Code

Get help with using AutoHotkey and its commands and hotkeys
User avatar
Tigerlily
Posts: 48
Joined: 04 Oct 2018, 22:31

Condensing Autohotkey Code

13 Jan 2019, 18:14

Hello Folks,

I looked around a bit and couldn't find a quick answer, maybe you know of one?

I started writing code the other day and realized that I was writing it inside more lines than necessary (due to my newness about coding and how AHK interpreter works in general)

for example, I had this code:

Code: Select all

!UP::
{
try 
{ 
Xl.Selection.Offset(-1,0).Select
} 
catch e 
{
}
} 
return

!DOWN::
{
try
{
Xl.Selection.Offset(1,0).Select
}
catch e
{ 
}
} return

!LEFT::
{ try { Xl.Selection.Offset(0,-1).Select
} catch e { 
}
} 
return

!RIGHT::
{ 
try 
{ 
Xl.Selection.Offset(0,1).Select
} 
catch e 
{ 
}
} 
return

and "minified" it to this:

Code: Select all

!UP::
{ try { Xl.Selection.Offset(-1,0).Select
} catch e {
}} return

!DOWN::
{ try { Xl.Selection.Offset(1,0).Select
} catch e { 
}} return

!LEFT::
{ try { Xl.Selection.Offset(0,-1).Select
} catch e { 
}} return

!RIGHT::
{ try { Xl.Selection.Offset(0,1).Select
} catch e { 
}} return
I read somewhere that combining multiple expressions into one line speeds up script performance in terms of speed, did what I do above by "minifying" my AHK code also increase my scripts speed performance? I tried to use a script that checks this but I'm too incompetent at this point to implement it correctly :lol:

Is there any way I could condense my code further (includingg on other code, not just what I posted above as an example)? Obviously Javascript has minifiers that puts everything into one line, but from my understanding, that is not possible with AHK (without some serious undertaking).

I'm wondering if anyone knows of a guide I could reference that can tell me what can go all into one line and what can't?

I'm using AHK v1.1.30.01. I haven't been able to dabble with v2 yet, but will the way code is written in v2 also help with more improved performance "one-liners" or condensed code?

Thanks a bunch for your response in advance! ;)
-TL
User avatar
Scr1pter
Posts: 771
Joined: 06 Aug 2017, 08:21
Location: Germany

Re: Condensing Autohotkey Code

13 Jan 2019, 18:38

I think you don't need the exception blocks in this case.
A while ago I made something similar and the try block was enough.
It's like:
“Try it, and if isn't possible, don't do anything.“

Regarding coding style:
No idea if it increases performance (not that I'm aware of),
but for me a good and clear overview is definitely more important.

I really suggest not to use the 2nd method.
You can omit the braces right after the hotkey and before the return, though.

Cheers!
I ignore every thread which contains the P-word :x
(Hint: It rhymes on Shython)
Please do not support cheaters!
Keyboard: Logitech G15 FE - Mice: Logitech G9 FE, G502 FE, G602 - OS: Windows 7 Pro 64 Bit - AHK version: 1.1.29.00
User avatar
Tigerlily
Posts: 48
Joined: 04 Oct 2018, 22:31

Re: Condensing Autohotkey Code

13 Jan 2019, 18:56

Thanks Scr1pter, will definitely take what you have said into account and practice.
I really suggest not to use the 2nd method.
You can omit the braces right after the hotkey and before the return, though.
Do you not suggest the 2nd method because its not as easy for others to read?


---


Would love to hear others opinions and experiences regarding this as well! :D Thanks all.
-TL
User avatar
Scr1pter
Posts: 771
Joined: 06 Aug 2017, 08:21
Location: Germany

Re: Condensing Autohotkey Code

13 Jan 2019, 19:21

Well, the most important thing is that it is readable for you.
If it's the case, then it's fine, but once you get problems and post the codes here, it might be more difficult to read, trace and understand.

How would you write if statements or loops for example?

Cheers!
I ignore every thread which contains the P-word :x
(Hint: It rhymes on Shython)
Please do not support cheaters!
Keyboard: Logitech G15 FE - Mice: Logitech G9 FE, G502 FE, G602 - OS: Windows 7 Pro 64 Bit - AHK version: 1.1.29.00
User avatar
kczx3
Posts: 720
Joined: 06 Oct 2015, 21:39

Re: Condensing Autohotkey Code

13 Jan 2019, 19:33

You severely need to indent your code better. The readability is quite difficult, for me.
swagfag
Posts: 1794
Joined: 11 Jan 2017, 17:59

Re: Condensing Autohotkey Code

13 Jan 2019, 19:42

ur code: !UP::try Xl.Selection.Offset(-1,0).Select
minifying ahk is pointless, unless ure writing a library or looping some super mission critical code. i can tell u, these hotkeys aren't it. inb4 someone chimes in that it adds up. yes, and it "subtracts back down" the next time it takes u more than 5 secs to figure out wtf u wrote yesterday

also i think this same-line-comma gimmick is supposed to be fixed in v2, so there's that
coffee
Posts: 96
Joined: 01 Apr 2017, 07:55

Re: Condensing Autohotkey Code

14 Jan 2019, 00:44

Tigerlily wrote:
13 Jan 2019, 18:14
Hello Folks,

I looked around a bit and couldn't find a quick answer, maybe you know of one?

I started writing code the other day and realized that I was writing it inside more lines than necessary (due to my newness about coding and how AHK interpreter works in general)

for example, I had this code:

I read somewhere that combining multiple expressions into one line speeds up script performance in terms of speed, did what I do above by "minifying" my AHK code also increase my scripts speed performance? I tried to use a script that checks this but I'm too incompetent at this point to implement it correctly :lol:

Is there any way I could condense my code further (includingg on other code, not just what I posted above as an example)? Obviously Javascript has minifiers that puts everything into one line, but from my understanding, that is not possible with AHK (without some serious undertaking).

I'm wondering if anyone knows of a guide I could reference that can tell me what can go all into one line and what can't?

I'm using AHK v1.1.30.01. I haven't been able to dabble with v2 yet, but will the way code is written in v2 also help with more improved performance "one-liners" or condensed code?

Thanks a bunch for your response in advance! ;)
The only purpose minification has in autohotkey is to make it harder for others to read. That's it.
Useless whitespaces and comments are omitted by the interpreter before execution, so there's no impact in that phase. There's only impact in the first run by design of any interpreted language, while the script is being parsed. Although whatever anyone comes back with regarding slowing or hogging down autohotkey during the parsing phase will be so absurd they will be only be able to convince themselves that it actually does *something* measurable by human standards, in their snippet sized scripts. Actual code lines carry far more weight than white space or commented lines.

Informal test after coming out of LoadFromFile() including overhead of executing the exe and anything else the debugging in visual studio may add, since i really won't waste my time in-depth testing this:
1 million inline comment lines and last line is a simple assignment ~500-600 ms
1 million blank lines and last line is simple assignment ~300ms.
100K lines of simple assignments ~600-700 ms.
1 million lines of simple assignments ~6000 ms, and ~3700 ms stopping after LoadIncludedFile(), skipping preparsing expressions and other stuff.
and I bet you a hershey's chocolate the majority of the 300ms of the blank lines test is because of external overhead unrelated to the routine that rolls through the lines.

I would say this would only matter if you are launching an external script repeatedly, like using Run("script.ahk") inside a crazy loop, but even then, for 99.9999999999999% of the scripts the operating system and the underlying ops of the run command will overshadow the skipping of whitespaces or comments. Disk will also affect read speeds.

Creating subexpressions only has an above marginal effect in v1, specially since people will rarely hit the number of expressions to actually make it worth it, as they will eventually stumble upon a statement that can't be placed inside an expression. In v2 subexpressions carry less impact than in v1, even less because of non-expression statements. Although if you keep it to yourself it's a non-issue, emphasis on bolded part here
Scr1pter wrote:
13 Jan 2019, 19:21
Well, the most important thing is that it is readable for you.
If it's the case, then it's fine, but once you get problems and post the codes here, it might be more difficult to read, trace and understand.
and waste people's time.

You can also (v2 only) place subexpressions in a more readable format using parenthesis, if you insist on this. You don't have to use a comma before each subexpression anymore, or bank roll them into a paragraph.

Code: Select all

; do stuff
(
	subexpr1,
	subexpr2,
	check ? itdo : itdont,
	subexpr3,
	subexpr4,
	subexpr5
)
;more stuff

Minification of this type (mangling, comment and useless whitespace removal) for browser-based javascript is mainly, mostly, majorly, primarily done to decrease file size so that the script is downloaded as fast as possible, can start running as soon as possible without increasing page load times and so that it doesn't affect the user experience, in addition to reducing network congestion. Which is also done for CSS files. None of which apply to autohotkey. With the, mostly placebo, second benefit being obfuscation for that library that nobody uses that's not gpl'd or mit'd and doesn't provide the uncompressed version.

You also have to consider the weakest link (or slowest in that case) in what you are interacting with. If you are going to be loop hitting or spamming any of file system, complex regex, COM, run commands and some types of dllcalls, it doesn't matter how many whitespaces or comments you remove, or how many subexpressions you cram in, because these operations can be orders of magnitude slower than typical script logic. Just like you can't make your car go faster by shaking out the floor mats outside to remove the weight of the dust.
You can still do this as a post processing stage, once you are done editing, defeating the convenience of the language itself.

There are however good practices in creating performant code in its own execution context, while still being readable and sometimes improving readability, that apply to pretty much any language, interpreted or compiled.
User avatar
Tigerlily
Posts: 48
Joined: 04 Oct 2018, 22:31

Re: Condensing Autohotkey Code

14 Jan 2019, 00:50

Scr1pter wrote:
13 Jan 2019, 19:21
Well, the most important thing is that it is readable for you.
If it's the case, then it's fine, but once you get problems and post the codes here, it might be more difficult to read, trace and understand.

How would you write if statements or loops for example?

Cheers!
Good point Scr1pter, while minimizing the amount of space that code takes up on my screen makes me feel better, it may be harder for people to help with any issues that I can't solve. To me it makes some things look more manageable, other times it creates a chaotic clutter. In my OP I am just making COM-based Hotkeys to interact with Excel without having Excel window as the main focus, so I'm not having any issues with that nor will I need help, so I like to smoosh it down and have it take as little real estate on my screen / in my code as possible.

This is how I was coding before I started trying to condense my code, I was being lazy with indents on OP:

Code: Select all

Loop,
{
	if (X = 0)
		{
		try
			{
			Xl := ComObjActive("Excel.Application")	
			Xl.Worksheets(A_Index).Activate
			Xl.ActiveSheet.Range("A1").Select
			}
				catch e
				{
				MsgBox Finished
				break
				}
	else if (X != 0)
		MsgBox Operation Failed
}
I've looked into various indentation styles and that makes the most sense to me heirarchically, but it also looks ugly and skeleton-like visually to me when I no longer need to work out the logic and bugs that arise.
kczx3 wrote:
13 Jan 2019, 19:33
You severely need to indent your code better. The readability is quite difficult, for me.
Is the above code a little better for you kczx3? How do you indent "better"?
swagfag wrote:
13 Jan 2019, 19:42
ur code: !UP::try Xl.Selection.Offset(-1,0).Select
minifying ahk is pointless, unless ure writing a library or looping some super mission critical code. i can tell u, these hotkeys aren't it. inb4 someone chimes in that it adds up. yes, and it "subtracts back down" the next time it takes u more than 5 secs to figure out wtf u wrote yesterday

also i think this same-line-comma gimmick is supposed to be fixed in v2, so there's that
I understand that my above code are simple hotkeys, however I am writing something that loops extremely fast and relies on the main loop to iterate very fast like you described, maybe not quite as extreme of a case as you're pointing to. The code I'm using currently works fine though for this project, but since I'm new to programming and AHK in general I want to see what my options are and what limits and best practices are out there. I think minifying AHK could be pointless, but there are reasons why it could be useful, if only just for peace of mind for those who prefer condensing their code for their own visual prefences and pleasure. I for one would like to put my curly brackets on the same line as my expressions and commands to cap it off instead of having to go one line down and put a single curly bracket for that whole line's purpose - I would rather it be a blank space for the sake of clarity for other readers. It would be nice to put my if-else and try-catch statements on one line when they are short enough.

What do you mean when you say " this same-line-comma gimmick is supposed to be fixed in v2" ??


Thanks for the replies folks! Much appreciate your insight and opinions. :D
-TL
User avatar
Tigerlily
Posts: 48
Joined: 04 Oct 2018, 22:31

Re: Condensing Autohotkey Code

14 Jan 2019, 01:03

coffee,

Thank you for such a well-put and detailed answer! This really helps me put things into more perspective. It also gives me greater interest in this "minification" process applied to AHK code for the sole use of obfuscation. I'm betting that at some point in the not so distant future I'll want to release some application(s) that require me to protect the code. I've read quite a bit on this forum about obfuscation of AHK code, and how every extra layer of difficulty you add in there is one more hoop that someone trying to steal your source code will have to go through, therefore making it that much harder. I know that AHK code cannot be 100% protected (as with I think any code, right?), but I still want to know what I would need to do and my options to do it if it comes down to me trying to obfuscate my code in a way that makes those kinds of theives as miserable as possible trying to break in.

Thanks again, I really appreciate your thorough answer and your insight here.

Cheers :beer:
coffee wrote:
14 Jan 2019, 00:44

The only purpose minification has in autohotkey is to .....
-TL
swagfag
Posts: 1794
Joined: 11 Jan 2017, 17:59

Re: Condensing Autohotkey Code

14 Jan 2019, 01:18

use a ternary for single line if-else
yeeeah, excel com is not what i had in mind when i said mission critical, but coffee already addressed that
this indent style looks ugly, cuz it makes no sense. its like a botched allmans. why does catch indent further than try? why do the brackets of if and try indent further than the keywords themselves? just do allmans
if u dont wanna look at code, u dont have to. put it in a function, put it in a different file
minifying ahk is pointless. the reasons uve outlined are nonreasons. ur clarity is someone elses muddiness. u cant accurately judge that
the "same-line-comma-gimmick" is chaining expressions with commas, which is supposed to yield +35% faster execution over not doing so
coffee
Posts: 96
Joined: 01 Apr 2017, 07:55

Re: Condensing Autohotkey Code

14 Jan 2019, 01:20

Code: Select all

Loop,
{
	if (X = 0)
		{
		try
			{
			Xl := ComObjActive("Excel.Application")	
This is where
There are however good practices in creating performant code in its own execution context
May come into play.

I don't know what's in the rest of your script, but I'm going to make the assertion that you don't need to retrieve the com reference in every iteration of the loop. Only 1 time, before you start looping. Since the loop's main purpose is to loop through sheets, not an array of com application references.


https://docs.microsoft.com/en-us/office ... eets.count
You can probably use "Worksheets.Count" to add an upper bound to the loop and you would only need to wrap the com retrieval in the try statement, which could probably reside outside the loop, with some changes to that whole block.
User avatar
kczx3
Posts: 720
Joined: 06 Oct 2015, 21:39

Re: Condensing Autohotkey Code

14 Jan 2019, 08:10

Tigerlily wrote:
14 Jan 2019, 00:50
kczx3 wrote:
13 Jan 2019, 19:33
You severely need to indent your code better. The readability is quite difficult, for me.
Is the above code a little better for you kczx3? How do you indent "better"?
Yes that is better. I prefer the One True Brace style for curly brackets however that is more so up to the programmer. See below. Also your sample was missing some closing brackets. Another thing that good code indentation and bracket placement can help with.

Code: Select all

Loop,
{
	if (X = 0) {
		try {
			Xl := ComObjActive("Excel.Application")	
			Xl.Worksheets(A_Index).Activate
			Xl.ActiveSheet.Range("A1").Select
		}
		catch e {
			MsgBox Finished
			break
		}
	}
	else if (X != 0) {
		MsgBox Operation Failed
	}
}
User avatar
sinkfaze
Posts: 455
Joined: 01 Oct 2013, 08:01

Re: Condensing Autohotkey Code

14 Jan 2019, 10:20

Well if you're looking for the ultimate in "minifying" you could set the above object in your auto-execute and run the hotkey as shown:

Code: Select all

xlo :=	{"!UP":{r:-1,c:0},"!DOWN":{r:1,c:0},"!LEFT":{r:0,c:-1},"!RIGHT":{r:0,c:1}}

!UP::
!DOWN::
!LEFT::
!RIGHT::
xl.Selection.Offset(xlo[A_ThisHotkey,"r"],xlo[A_ThisHotkey,"c"]).Select
return
But if you're looking for a better balance on readability:

Code: Select all

!UP::
!DOWN::
!LEFT::
!RIGHT::
if	(A_ThisHotkey="!UP")
	xl.Selection.Offset(-1,0).Select
else if	(A_ThisHotkey="!DOWN")
	xl.Selection.Offset(1,0).Select
else if	(A_ThisHotkey="!LEFT")
	xl.Selection.Offset(0,-1).Select
else	xl.Selection.Offset(0,1).Select
return
I'm not sure what the necessity of try/catch is in your code, but the only thing I can reasonably see that you'd need to test for is the sheet boundaries with respect to which cell you'd like to select. That could easily be done prior to execution.
User avatar
jeeswg
Posts: 5577
Joined: 19 Dec 2016, 01:58
Location: UK

Re: Condensing Autohotkey Code

14 Jan 2019, 10:39

I find Allman style the clearest.

Code: Select all

Loop
{
	if (X = 0)
	{
		try
		{
			Xl := ComObjActive("Excel.Application")
			Xl.Worksheets(A_Index).Activate
			Xl.ActiveSheet.Range("A1").Select
		}
		catch e
		{
			MsgBox Finished
			break
		}
	}
	else if (X != 0)
		MsgBox Operation Failed
}
Adding commas here might be faster.

Code: Select all

		try
		{
			Xl := ComObjActive("Excel.Application")
			, Xl.Worksheets(A_Index).Activate
			, Xl.ActiveSheet.Range("A1").Select
		}
User avatar
kczx3
Posts: 720
Joined: 06 Oct 2015, 21:39

Re: Condensing Autohotkey Code

14 Jan 2019, 11:38

sinkfaze wrote:
14 Jan 2019, 10:20
Well if you're looking for the ultimate in "minifying" you could set the above object in your auto-execute and run the hotkey as shown...
I actually think that is completely clear and concise. Maybe don't define the whole object on a single line but that's very similar code to what I'd have written.

Return to “Ask For Help”

Who is online

Users browsing this forum: au6, Google [Bot], paik1002 and 77 guests