tnichol
tnichol

Reputation: 155

Groovy file.append() vs file.newWriter()

I have written several Groovy programs that write flat files using file.write() and file.append() or simply "file << string". I recently came across some information when researching this method where people said that this may be inefficient as appending to a file means the append opens the file, finds the end, writes to it, and closes it each time the append is called. In some programs I may call this numerous times as I write to a file after selecting data from a database.

I further read that using a file writer is more efficient, for example declaring

fileWriter = new file.newWriter() 

and then issuing

fileWriter.write() 

instead. My question is, what are other people doing and does anybody know at about what point it would be worth considering a change to using a file writer instead? I haven't actually noticed a performance hit to this point; however, I have several more programs to write that will produce some large flat files and if it makes sense to use the file writer I'd rather change my previous programs to use it now rather than later.

Upvotes: 1

Views: 5190

Answers (1)

Opal
Opal

Reputation: 84784

A simple benchmark to illustrate the problem:

@Grab(group='org.gperfutils', module='gbench', version='0.4.2-groovy-2.1')

def b = benchmark {
      'append' {
          def f = File.createTempFile('file', 'append')
          (1..1000).each {
              f.append(it.toString())
          }
      }
      'writer' {
          def f = File.createTempFile('file', 'writer')
          def w = f.newWriter()
          (1..1000).each {
              w.write(it.toString())
          }
      }
}
b.prettyPrint()

Upvotes: 5

Related Questions