How to Write Energy-Efficient Code

Diseph Dum-Igoni
12 min readJun 13, 2024

--

Credit: NASA Simulation of Carbon Dioxide Emission in the atmosphere.

Your code might be impressively optimized, but is it environmentally friendly?

In this article, we’ll explore how the code you write impacts the environment and practical ways to make your code greener. You’ll learn 35 techniques and strategies that reduce the carbon footprints of your programs, making your code part of the solution rather than the problem. Let’s get to it.

What is a Carbon Footprint?

Photo Credit: phys.org

Every human activity emits some energy to the environment. A Carbon Footprint measures gaseous emissions released to the environment as a result of these activities. It is known as Carbon Equivalent, often denoted as CO2eq.

Why Does my Code Release Carbon?

When you write and run code, the execution process involves a series of computations and data manipulations that consume electrical energy. This electrical energy largely comes from burning fossil fuels, which emit gases like carbon dioxide into the atmosphere.

Simply, when a program is run, the CPU fetches, decodes, and executes instructions from that program. This involves multiple hardware components like the RAM, CPU, etc., all of which consume electrical energy. A typical CPU running at full capacity can consume between 65–100 watts of power. Additionally, a program communicating over the internet (e.g., making API calls, accessing cloud services) requires energy for data transfer.

How is a Carbon Footprint Measured?

Websites such as the Green Web Foundation’s CO2.js enable developers to estimate the emissions related to their apps, websites, and software. Carbon footprint from your code can also be calculated with online tools and programming frameworks, such as CarbonFootprint, CodeCarbon and Eco2AI for Python, or other tools provided by sustainability organizations.
Intel’s Power Gadget and Microsoft Joulemeter can also be used to measure the energy emission from your programs.

As Programmers, our role is to build applications that emit less carbon without affecting application functionality.

Photo credit: Geekflare

Strategies for Writing Green Code

The following are practical ways to reduce the carbon footprint of your code. Majority are general strategies while some may be specific to certain fields.

1. Choose Efficient Data Structures and Algorithms

Most Relevant: All fields

Choosing the right data structures for specific tasks can reduce energy usage. For example, using hash maps for data retrieval instead of searching through arrays can save processing time and energy. Similarly, algorithms that minimize time complexity, such as binary search instead of linear search for sorted data, can lead to significant efficiency gains. Consider the difference between a bubble sort and a quicksort algorithm. While both achieve the same result, quicksort is more efficient because it reduces computational load and, consequently, the energy consumed. Choosing the right algorithm for the task can increase energy savings.

2. Use Green Hosting Providers

Most Relevant: Fields that utilize the Cloud

Your code may be green, but your external host may be running on non-renewable energy. Use hosting providers that have committed to using renewable energy and have efficient data center designs. Hosting providers that use solar, wind, or hydroelectric power reduce reliance on fossil fuels thus lowering carbon emissions. Cloud centers like Google Cloud, Equinix, Azure, and AWS have committed to making greener solutions.

3. Use efficient Programming Languages and Frameworks

Most Relevant: All Fields

In a study conducted by a team of six Portuguese researchers, 10 benchmark problems were implemented in 23 different programming languages to test how much Energy and Time each would use. It was found that each programming language have varying impacts on energy consumption. Compiled Languages, C and C++, performed best, while interpreted languages like Python was less energy-efficient due to higher runtime overhead.

Even still energy emission will vary with the task to be executed. For instance, in implementing a binary tree, C performed most efficient, whilst Rust performed best in implementing a Fasta. You can read the full paper here.

The same is also true for frameworks. Choose frameworks designed with energy efficiency in mind. For example, lightweight web frameworks like Flask can be more energy efficient. While considering energy efficiency in choosing languages, it is important to note that faster load times do not necessarily lead to energy savings.

“We can have languages with very similar energy consumptions and completely different execution times…”-source.

4. Cache Frequent Data

Most Relevant: All Fields

Caching involves storing frequently accessed data in a temporary storage location for quick retrieval, reducing the workload on servers and databases. By accessing data from the cache, you reduce the CPU cycles needed and decrease the amount of data transferred over network. Fewer database queries and less disk I/O operations mean less strain on servers, which can lead to reduced cooling requirements and overall energy savings. In-memory caching systems like Redis or Memcached are excellent choices for high-performance caching solutions.

5. Use Efficient Cloud Resources

Most Relevant: Fields that utilize the Cloud

Efficient cloud resource management ensures that computing resources are only used when necessary, thus minimizing idle time and overall energy consumption. To achieve this:

  • Use Auto-Scaling to automatically adjust the number of active servers based on current demand.
  • Use Serverless computing models to run code in response to events without provisioning or managing servers, such as AWS Lambda.
  • Analyze and choose the appropriate instance types and sizes for specific workloads to avoid over-provisioning and underutilization.
  • Use container orchestration platforms like Kubernetes to efficiently manage application deployment, scaling, and operations.
Photo Credit: Sam Atmaramani

6. Minify your Code

Most Relevant: Web Development.

Minification involves removing unnecessary characters, including white spaces, comments, and line breaks, without affecting code functionality. This can reduce the size of your source files and the time for data transfer. Tools like UglifyJS for JavaScript, CSSNano for CSS, and HTMLMinifier for HTML can automate this process.

7. Automate Where You Can

Most Relevant: All Fields

Automation involves using tools and scripts to perform repetitive tasks. It reduces the need for manual intervention and ensues efficient resource use as processes consume fewer resources.

8. Discard Unused Code

Most Relevant: All Fields

Remove code that has no functionality for your program; that is, your program will function the same with or without it. This helps improve performance by reducing the overall size of the application. Smaller codebases require less computational resources to run, saving energy. Additionally, detect and remove loops which cannot achieve their intended purpose and needlessly consume energy.

9. Write Clean and Reusable Code

Most Relevant: All Fields

Writing clean, reusable code involves creating well-organized, easy-to-read, and modular code that can be reused across different parts of a project or even in different projects. This will avoid duplicating efforts and reduces the overall amount of code that needs to be written, tested, and maintained.

Clean code is also easier to understand which means less time and computational power will be spent on debugging and refactoring. This efficiency translates into fewer resources used over the lifecycle of the application. Employ the DRY principle “Don’t Repeat Yourself” and also use clear documentation.

Photo Credit: VPsCity

10. Resource Management

Most Relevant: All Fields

Managing resources efficiently ensures that no computational power is wasted. Proper resource management allows for scalable applications that can handle varying loads with minimal resources. Use efficient memory management techniques such as garbage collection and memory pooling. Also consider load balancing to distribute workloads evenly across servers. When working with data, use generators or streams to handle data in smaller chunks instead of processing an entire dataset in memory.

11. Compress Your Data Files

Most Relevant: All Fields

Use Lossless compression techniques to compress data without affecting its contents; thereby increasing the speed to read, write and transfer files over the network. You can also apply compression techniques to images.

12. Optimize your Database

Most Relevant: All fields

Database optimization involves improving the performance and efficiency of database operations to handle queries and transactions more effectively. Efficient databases require less computational power and energy to operate. Use indexing, query optimization, and normalization techniques to implement this.

13. Use Parallel Processing

Most Relevant: Data Fields and Software Engineering

Parallel Processing is the breaking of whole tasks into smaller processes and running them simultaneously without blocking each other. By running tasks in parallel, CPU and memory resources are used more efficiently, reducing idle time and energy waste. Multi-threading techniques and distributed computing frameworks like Hadoop can help achieve this.

14. Use Batch Processing

Most Relevant: All Fields

Batch processing involves grouping similar tasks (jobs) into a single batch and executing them at a go in periods of low demand. This reduces the need for constant resource allocation and deallocation. For example, Machine Learning models trained on large datasets are better scheduled in batches to efficiently use GPU/TPU resources.

Photo Credit: AllGeo Blog

15. Schedule Tasks

Most Relevant: All Fields

Job scheduling refers to the method of controlling the order and timing of jobs (tasks) to optimize resource use. It ensures that jobs are run at the appropriate time, in the correct order, and with the necessary resources. To achieve this:

  • Assign priorities to tasks so that critical jobs are processed first.
  • Schedule tasks such as updates, to run at specific times, such as during nights or weekends, to leverage periods of low energy consumption.

16. Consider the Energy Impact of AI and ML Models

Most Relevant: AI and Machine Learning

Training AI and ML models can be resource-intensive and consume significant energy. Use techniques like transfer learning, where a pre-trained model is fine-tuned on a specific task, to reduce the amount of training needed. Additionally, consider model quantization, which reduces the precision of model weights, and thus reduces the computational power needed for inference.

17. Speed-Up Network Traffic

Most Relevant: All Fields

Network traffic optimization involves reducing the amount of data transmitted over a network to improve performance and reduce energy consumption. Use efficient data serialization formats like Protocol Buffers or MessagePack instead of JSON or XML to reduce the size of transmitted data. Compress data before transmission to minimize the amount of data sent over the network. Also, minimize the frequency of network requests by caching responses and using batch requests.

18. Monitor and Profile Your Code

Most Relevant: All Fields

Code profiling involves analyzing your code to identify performance bottlenecks and areas where optimization is needed. It allows you to focus your efforts on the parts of your code that consume the most resources. Identify and optimize functions that consume the most CPU, memory, or disk I/O. Tools like PyCharm, Py-Spy, and JProfiler for Java can help in profiling your code. Additionally, regular monitoring of your applications ensures they run efficiently over time. Use monitoring tools like New Relic or Prometheus to track resource usage and performance metrics.

19. Use Efficient File I/O

Most Relevant: All Fields

Efficient file input/output operations reduce disk usage and energy consumption. It involves optimizing how data is read from and written to files. To achieve this, minimize unnecessary file operations, such as opening and closing files multiple times. Use buffering techniques to read and write data in chunks, reducing the number of I/O operations, and use binary formats for storing data instead of text formats when possible.

20. Minimize External Dependencies

Most Relevant: All Fields

Relying on many external libraries and frameworks can bloat your codebase and increase the number of resources needed to run your application. Choose lightweight alternatives and remove unnecessary dependencies to minimize your codebase’s size and complexity.

21. Effective Power Management

Most Relevant: All Fields

Power management involves using software and hardware features to reduce power consumption when resources are not in use. For example, modern CPUs support dynamic frequency scaling (also known as CPU throttling), which adjusts the processor’s clock speed based on the current workload. Implement power-saving modes and sleep states to reduce energy usage during periods of inactivity.

22. Minimize Background Tasks

Most Relevant: All Fields

Background tasks, such as scheduled jobs and daemon processes, can consume significant resources if not managed properly. Minimize the number of background tasks and ensure they are optimized for efficient resource usage. Additionally, use scheduling and throttling techniques to control the frequency and intensity of background tasks.

23. Use Virtualization and Containerization

Most Relevant: All Fields

Virtualization involves creating virtual instances of hardware resources, while containerization involves creating lightweight, portable containers that can run applications consistently across different environments. Virtualization allows multiple virtual machines (VMs) to run on a single physical server, maximizing resource utilization. Containerization, using tools like Docker, provides a more lightweight and efficient alternative to VMs, reducing the overhead associated with running multiple applications on the same hardware.

Photo Credit: JRebel

24. Optimize Content Delivery

Most Relevant: Web Development

This involves techniques to ensure that web content is delivered to users as quickly and efficiently as possible. Faster delivery of content means servers spend less time handling each request, reducing the overall resource consumption. Be sure to use Content Delivery Networks (CDNs) to distribute contents to the user. This ensures that data is delivered from the nearest server to the user, minimizing travel distance and latency.

25. Use Code Bundling and Lazy Loading

Most Relevant: Web Development

Code bundling involves combining multiple JavaScript or CSS files into a single file to reduce the number of HTTP requests needed to load a webpage. This can improve load times and reduce server load. Webpack is a popular tool for bundling code in JavaScript projects. Lazy loading involves loading resources on-demand. For example, images and scripts can be loaded only when they are about to enter the viewport. This reduces the initial load time and minimizes resource consumption.

26. Use Efficient Test Strategies

Most Relevant: All Fields

Optimize your testing strategies to minimize the resources needed for testing. Use automated testing frameworks to reduce manual testing efforts and use efficient test data management techniques to minimize the size and complexity of test data.

27. Analyze Tracked Data

Most Relevant: Web Development, Software Engineering

If your script uses a tracking tool but the collected data is not being analyzed, then you should not be tracking data in the first place. Not using data analytics increases data storage, load time and use of 3/4/5G which pollutes five times more.

28. Employ Modular Design

Most Relevant: All Fields

When writing your programs, have efficiency in mind. Use modular design principles to create reusable and maintainable components. Additionally, consider the overall architecture of your application and choose efficient patterns and frameworks that minimize resource consumption.

29. Avoid Unnecessary or Excessive Assets

Most Relevant: Web and App Development

Reducing the use of large media files like images, videos, and other assets can decrease the bandwidth needed and reduce the energy consumption of data centers and network infrastructure.

30. Apply Software Updates and Patches

Most Relevant: All Fields

Regularly updating and patching your software ensures that you benefit from the latest performance improvements and security enhancements. Software updates often include optimizations that can reduce resource consumption and improve efficiency.

Other Ways

31. Regularly attend trainings, workshops and take courses on sustainable coding practices.

32. Communicate and help your users understand the environmental impact of their actions and provide them with sustainable alternatives.

33. Participate in green coding initiatives, conferences, projects and collaborate with other developers to help share knowledge and drive collective efforts towards more sustainable coding practices.

34. Narrow your google search as much as Possible.

35. Managers and Team Leads should also adopt a Green Mindset and foster a culture of sustainability within development.

Call-To-Action

Photo Credit: Jason Maden

The environment keeps degrading each day and our code is contributing to it, but by adopting sustainable coding practices, you and I can make a positive difference.

One step you should take after reading this is to share this article with your programmer friends and colleagues. Also be sure to check out the resources provided below for other ways you can help. Let’s make the earth greener in our little way. Together we achieve more!

--

--