{"meta":{"title":"Refactoring for environmental sustainability","intro":"Copilot Chat can suggest ways to make code more environmentally friendly.","product":"GitHub Copilot","breadcrumbs":[{"href":"/en/copilot","title":"GitHub Copilot"},{"href":"/en/copilot/tutorials","title":"Tutorials"},{"href":"/en/copilot/tutorials/copilot-cookbook","title":"GitHub Copilot Cookbook"},{"href":"/en/copilot/tutorials/copilot-cookbook/refactor-code","title":"Refactor code"},{"href":"/en/copilot/tutorials/copilot-cookbook/refactor-code/refactor-for-sustainability","title":"Refactor for sustainability"}],"documentType":"article"},"body":"# Refactoring for environmental sustainability\n\nCopilot Chat can suggest ways to make code more environmentally friendly.\n\nCode that is inefficient in its use of computational resources can lead to higher energy consumption, which has a negative impact on the environment. Examples of such code include algorithms with high time complexity, excessive memory usage, and unnecessary processing.\n\nCopilot Chat can help identify inefficient algorithms or resource-intensive operations in your code that contribute to higher energy consumption. By suggesting more efficient alternatives, it can help reduce the environmental impact of your software.\n\n## Example scenario\n\nThe following Python code reads a large text file and counts the number of lines. However, it loads the entire file into memory, which can be inefficient for large files and lead to higher energy consumption. It also manually counts the lines instead of using built-in functions.\n\n```python id=inefficient-code\ndef count_lines(filename):\n    with open(filename, 'r') as f:\n        data = f.read()\n        lines = data.split('\\n')\n        count = 0\n        for line in lines:\n            count += 1\n        return count\n\nprint(count_lines('largefile.txt'))\n```\n\n## Example prompt\n\nHere is an example prompt you can use with Copilot Chat to refactor the above code for better environmental sustainability:\n\n```copilot copy prompt ref=inefficient-code\nRefactor this code to improve its environmental sustainability by reducing memory usage and computational overhead.\n```\n\n## Example response\n\n> \\[!NOTE] Copilot Chat responses are non-deterministic, so you may get a different response from the one shown here.\n\nCopilot suggests using a generator expression to read the file line by line, which reduces memory usage. It also uses the built-in `sum` function to count the lines more efficiently.\n\n```python\ndef count_lines(filename):\n    with open(filename, 'r') as f:\n        return sum(1 for _ in f)  # Efficiently counts lines without loading all into memory\n\nprint(count_lines('largefile.txt'))\n```\n\n## Further reading\n\n* [Prompt engineering for GitHub Copilot Chat](/en/copilot/concepts/prompting/prompt-engineering)\n* [Best practices for using GitHub Copilot](/en/copilot/get-started/best-practices)"}