Looking for ways to make code more efficient

Post Reply
User avatar
FlorianK
Posts: 238
Joined: Fri Jun 11, 2010 9:56 am
Location: Cologne, Germany

Looking for ways to make code more efficient

Post by FlorianK » Thu Aug 22, 2013 1:56 pm

I'm developing some basic version control system for Realflow. The following function is part of it and it steps through a Domain's export resources, looks if it is activated and then (in a different function) increments the foldernames.

Code: Select all

	allGFD = scene.getGridDomains()
		if len(allGFD) != 0:
			for dom in allGFD:
				if dom.isExportResourceActive(EXPORT_GRID_DOMAIN_GFC):
					exportPath = dom.getExportResourcePath(EXPORT_GRID_DOMAIN_GFC)
					newPath = incrementVersionAtPath(exportPath)
					if newPath != -1:
						dom.setExportResourcePath(EXPORT_GRID_DOMAIN_GFC, newPath)
					exportPath = ''

				if dom.isExportResourceActive(EXPORT_GRID_DOMAIN_PROXY):
					exportPath = dom.getExportResourcePath(EXPORT_GRID_DOMAIN_PROXY)
					newPath = incrementVersionAtPath(exportPath)
					if newPath != -1:
						dom.setExportResourcePath(EXPORT_GRID_DOMAIN_PROXY, newPath)
					exportPath = ''
#etc
Like this, it is a lot of text. I'd preferably use just one if- structure and push the constants such as EXPORT_GRID_DOMAIN_PROXY as variables through the if. Unfortunately I am not sure how to be doing that, so I am very thankful for any hints.

User avatar
enrique
Site Admin
Posts: 42
Joined: Fri Jun 17, 2011 9:44 am

Re: Looking for ways to make code more efficient

Post by enrique » Thu Aug 22, 2013 3:37 pm

You can create a list with all the resources you want to deal with like this:

Code: Select all

myExportedStuff = [EXPORT_GRID_DOMAIN_GFC, EXPORT_GRID_DOMAIN_PROXY, blablabla]
Then you just do what you are currently doing but iterating through that list...

Code: Select all

allGFD = scene.getGridDomains()
      if len(allGFD) != 0:
         for dom in allGFD:
            for asdf in myExportedStuff:
               if dom.isExportResourceActive(asdf):
                  exportPath = dom.getExportResourcePath(asdf)
                  newPath = incrementVersionAtPath(exportPath)
                  if newPath != -1:
                     dom.setExportResourcePath(asdf, newPath)
                  exportPath = ''
you can as well isolate the repeated code into a function and apply that function to every element in the list like this:

Code: Select all

vec = [-2, 3, -7, 5, -11]
[abs(x) for x in vec]
Enrique Turegano
RealFlow | Cinema4D developer

User avatar
FlorianK
Posts: 238
Joined: Fri Jun 11, 2010 9:56 am
Location: Cologne, Germany

Re: Looking for ways to make code more efficient

Post by FlorianK » Fri Aug 23, 2013 9:58 am

Thank you very much.

Post Reply