Speeding Up Code

I'm made a script that iterates through all windows and restores minimized windows. However, the script is quite slow. I'm wondering how to speed it up. I believe part of why the code is so slow is that it's looking at every process instead of every foreground process. Is it possible to do something like "repeat with p in every foreground process" or speed up this script through other means?

on run {input, parameters}
	set windowNames to {}
	tell application "System Events"
		repeat with p in every process
			repeat with w in every window of p
				if value of attribute "AXMinimized" of w is true then
					set value of attribute "AXMinimized" of w to false
				end if
			end repeat
		end repeat
	end tell
end run

Replies

This code decreases run time of the previous code by at least 90%. It's a huge improvement.

on run
	tell application "System Events"
		set foregroundApps to (every process whose background only is false) as list
		repeat with foregroundApp in foregroundApps
			set appName to name of foregroundApp
			if exists (window 1 of process appName) then
				if contents of appName is not "" then
					repeat with w in every window of foregroundApp
						if value of attribute "AXMinimized" of w is true then
							set value of attribute "AXMinimized" of w to false
						end if
					end repeat
				end if
			end if
		end repeat
	end tell
end run

You can speed it up a bit more by not bothering with the check for a window, as just getting the windows will always return a list and avoid the duplication in getting windows. Better yet, you can usually reduce overhead by having an application do as much as possible with any given call, for example:

tell application "System Events"
   set foregroundApps to (processes whose background only is false)
   repeat with anApp in foregroundApps
      set minimizedWindows to (windows of anApp where value of attribute "AXMinimized" is true)
      repeat with aWindow in minimizedWindows
         tell aWindow to set value of attribute "AXMinimized" to false
      end repeat
   end repeat
end tell

In this example you can go even further by doing something like getting the (windows of (processes whose background only is false) where value of attribute "AXMinimized" is true), but there are diminishing returns for increased noise and the performance of complex expressions depends a bit on the particular application.