{"meta":{"title":"为环境可持续性进行重构","intro":"Copilot Chat 可以建议使代码更加环保的方法。","product":"GitHub Copilot","breadcrumbs":[{"href":"/zh/copilot","title":"GitHub Copilot"},{"href":"/zh/copilot/tutorials","title":"教程"},{"href":"/zh/copilot/tutorials/copilot-cookbook","title":"GitHub Copilot 指南"},{"href":"/zh/copilot/tutorials/copilot-cookbook/refactor-code","title":"重构代码"},{"href":"/zh/copilot/tutorials/copilot-cookbook/refactor-code/refactor-for-sustainability","title":"重构以实现可持续发展"}],"documentType":"article"},"body":"# 为环境可持续性进行重构\n\nCopilot Chat 可以建议使代码更加环保的方法。\n\n使用计算资源效率低下的代码可能会导致更高的能耗，这对环境产生了负面影响。 此类代码的示例包括时间复杂性高、内存使用率过高和不必要的处理算法。\n\nCopilot Chat 可以帮助识别代码中低效的算法或资源密集型操作，从而提高能耗。 通过建议更高效的替代方法，它可以帮助减少软件的环境影响。\n\n## 示例方案\n\n以下 Python 代码读取大型文本文件并计算行数。 但是，它会将整个文件加载到内存中，这对于大型文件来说可能效率低下，并导致更高的能耗。 它还会手动计数行数，而不是使用内置功能。\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## 示例提示\n\n以下是一个示例提示词，你可以配合 Copilot Chat 使用它来重构上述代码，以提升环境可持续性：\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## 示例响应\n\n> \\[!NOTE]\n> Copilot Chat 响应是不确定的，因此你可能会得到与此处所示的响应不同的响应。\n\nCopilot 建议使用生成器表达式逐行读取文件，从而减少内存使用量。 它还使用内置 `sum` 函数更有效地计算行数。\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## 延伸阅读\n\n* [GitHub Copilot 对话助手的提示设计](/zh/copilot/concepts/prompting/prompt-engineering)\n* [使用 GitHub Copilot 的最佳做法](/zh/copilot/get-started/best-practices)"}