Tech Tip #22: Buffer your reads and writes

Writing one line at a time means one system call per line.

Video created by explainapaper.com

The problem

Unbuffered I/O turns every small read or write into its own trip to the operating system and the disk. Log files, CSV exports and socket writes are the usual culprits.

The fix you can use today

  • Wrap streams in a buffered reader or writer (BufferedWriter, io.BufferedWriter, bufio).
  • Write in chunks, and stream large files instead of loading them whole.
  • Flush when you need durability, not after every line.

GreenCode researchers list unbuffered reads and writes among the worst energy wasters in code.

Tools that help

  • GreenCode Constitution skill (GreenCode researchers): open-source energy principles and a catalogue of 37 energy anti-patterns that an AI coding agent can follow to find and fix waste like this
  • green-languages (GreenCode researchers): a command-line tool that measures the energy of whole programs or marked sections of code, across languages

How GreenCode helps

GreenCode helps tackle this by rewriting flagged code one piece at a time. It writes any missing tests first, and returns every change for a person to approve. More on this.

Tags

#performance#java#python

Sources

All GreenCode Tech Tips

  • Tip #22
  • For Developers
  • Category Code efficiency
  • Format short video
GreenCode

Want this checked on your own system? Talk to the GreenCode team.

Get in touch