Faster file renaming?

Please include error handling before going any further. The unhandled errors are:

  • err argument to visit
  • error returned by os.Rename
  • error returned by filepath.Walk

https://pocketgophers.com/error-checking-while-prototyping/ describes my method for handling errors without having to think too much about them (until they are encountered). https://github.com/kisielk/errcheck is a tool to help find unhandled errors.

Now, onto you question.

Start by profiling your program. Profiling will help you know what part of your program is using the most time, memory, etc. You need to know what is happening to know what to improve or even if there are useful improvements you can do. https://blog.golang.org/profiling-go-programs gives an example of how to do so and the thinking required.

I have not profiled your code, but have made some guesses based on the principle that the fastest code is the code that does not exist.

strings.Replace searches the string to find where the extension is. The extension is always at the end, and since the extension is already known (it is stored in ext), newname := path[:len(path)-len(ext)] + *flagExt will give the same result without needing filepath.Dir, filepath.Base, filepath.Join, or strings.Replace.

Also, the code you posted does not do what it indicates it should do. The description for flagPath says it should be searching for “jpg files”, but if ext != "" actually checks for files with extensions.

1 Like