logo
Menu
Unleash Amazon Q Developer: From Code Creation to Legacy Code Optimization (Part 1)

Unleash Amazon Q Developer: From Code Creation to Legacy Code Optimization (Part 1)

In this blog post, we will explore the power of Amazon Q Developer within Visual Studio Code to develop code for listing Amazon S3 buckets in a specific region. We will start by writing the initial code with the assistance of the Amazon Q Developer Agent, and then compare it to an existing inefficient "legacy" code. Subsequently, we will optimize the legacy code through Amazon Q Developer’s guidance, resulting in a significant reduction in execution time.

Haowen Huang
Amazon Employee
Published May 8, 2024

Overview

As you may know, AWS recently announced the general availability of Amazon Q Developer, a generative AI–powered assistant that reimagines your experience across the entire software development lifecycle (SDLC). The official blog is shown here:
Amazon Q Developer can help you understand, build, extend, and operate AWS applications. You can ask questions about AWS architecture, your AWS resources, best practices, documentation, support, and more. Amazon Q is constantly updating its capabilities, so your questions receive the most contextually relevant and actionable answers.
In this blog post, we will explore how to use Amazon Q Developer to handle real-world coding requirements within the Visual Studio Code IDE environment. We will focus on writing effective and high-quality code to list the Amazon S3 buckets in a specific region as an example.
Before proceeding, please refer to the following official AWS documentation for tutorials on setting up Amazon Q Developer with Visual Studio Code:

Writing the Initial Code

First of all, let’s use the Amazon Q Developer Agent to write the initial code. You can refer to the following official AWS documentation to learn more about how to use it:
It’s very easy to write the initial code with the help of Amazon Q Developer Agent, as shown in the following screenshot:
Using Amazon Q Developer Agent to generate code
Using Amazon Q Developer Agent to generate code
The Prompt I used in the Amazon Q chat panel is as follows:
“/dev Write code to list all the Amazon S3 buckets in the `ap-east-1` region and output their names, along with the total execution time of the script.”
For your convenience, I have included the code snippets generated by Amazon Q Developer Agent, as shown below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import time
import boto3

def list_s3_buckets_in_region(region_name):
"""
Lists all the Amazon S3 buckets in the specified region.

Args:
region_name (str): The AWS region name.

Returns:
list: A list of bucket names.
"""

s3_client = boto3.client('s3', region_name=region_name)
response = s3_client.list_buckets()
buckets = []

for bucket in response['Buckets']:
bucket_region = s3_client.get_bucket_location(Bucket=bucket['Name'])['LocationConstraint']
if bucket_region == region_name:
buckets.append(bucket['Name'])

return buckets

def main():
start_time = time.time()
region_name = 'ap-east-1'
buckets = list_s3_buckets_in_region(region_name)

print(f"Number of buckets found in {region_name} region: {len(buckets)}")
print("\nBucket names:")
for bucket_name in buckets:
print(bucket_name)

end_time = time.time()
execution_time = end_time - start_time
print(f"\nTotal execution time: {execution_time:.2f} seconds")

if __name__ == "__main__":
main()
After run the above Python code, you will get the output as shown in the following screenshot:
Using Amazon Q Developer to generate code - output
Using Amazon Q Developer to generate code - output
WOW! In just one minute, the Amazon Q Developer Agent has written a complete code to list the Amazon S3 buckets in a specific region as an example. The total program execution time is 1.37 seconds!

Comparing with Legacy Code

We've experienced firsthand the power of the Amazon Q Developer Agent to quickly write new code, but can it help us modify legacy code? As developers, we wrote a lot of code before Amazon Q Developer was introduced, so we also hope Amazon Q Developer can help us modify legacy code as well.
The following “legacy” code was written by me without much consideration for efficiency and code execution speed. The main function of the code is to list all the S3 buckets in a specific region and output their names, along with the total execution time of the script. It is the same requirement as we asked Amazon Q Developer to do in the previous chapter.
I have provided the complete “legacy” code below for your reference:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# The following code counts the number of S3 Buckets in a specified region, lists the names of the S3 Buckets in that region,
# and records the program's execution time.
#
# Author: Haowen Huang
# Date: May 5, 2024

import time

def main():
start_time = time.time() # Record the start time

# Your existing code here
from aws_cdk import (
App, Stack, CfnOutput
)
import boto3
from constructs import Construct

class MyStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

# Create an S3 client for the specific region
s3_client = boto3.client('s3', region_name='ap-east-1')

# Get a list of all buckets in the specific region
all_buckets = []
response = s3_client.list_buckets()
for bucket in response['Buckets']:
bucket_region = s3_client.get_bucket_location(Bucket=bucket['Name'])['LocationConstraint']
if bucket_region == 'ap-east-1':
all_buckets.append(bucket['Name'])

print(f"Number of buckets found in ap-east-1 region: {len(all_buckets)}")
print("\nBucket names:")
for bucket_name in all_buckets:
print(bucket_name)

# Output the list of bucket names
for i, bucket_name in enumerate(all_buckets):
CfnOutput(self, f"Bucket-{i}", value=bucket_name)

app = App()
MyStack(app, "haowen-cdk-app-list-S3-demo")
app.synth()

end_time = time.time() # Record the end time
execution_time = end_time - start_time
print(f"\nTotal execution time: {execution_time} seconds")

if __name__ == "__main__":
main()
After running the above Python code, you will get the output as shown in the following screenshot:
Legacy code running result
Legacy code running result
As you can see, the total execution time of this “legacy” code is almost 4.33 seconds, which is far behind the code generated by Amazon Q Developer Agent in the previous chapter.
After seeing this, you're probably as curious as I am: why is this legacy code running so slowly? Can Amazon Q Developer help us diagnose this slow code and optimize it to run more efficiently? We'll unravel this mystery in the next chapter.

Optimizing Legacy Code

First of all, let’s send the legacy code to Amazon Q. To send your code to Amazon Q, following these steps:
  • 1. Highlight a section of a code file in your IDE, as shown below.
  • 2. Right-click on the highlighted code to open a context window. Choose “Send to Amazon Q”, and then select “Send to prompt”.
Sending the legacy code to Amazon Q
Sending the legacy code to Amazon Q
If you choose “Send to prompt”, Amazon Q will copy the highlighted code to the chat panel, where you can enter any questions or prompts you have regarding the code, as illustrated in the screenshot provided below.
Enter prompts in the Amazon Q panel
Enter prompts in the Amazon Q panel
The Prompt I used in the Amazon Q chat panel is as follows:
“Please carefully review the code I have written. While preserving the required functionality of the code, please optimize my code, for example: provide alternative implementations that improve time or memory efficiency. Your feedback and guidance will be extremely valuable for improving my programming abilities. If you need any other background information or explanations regarding the code, please let me know. Finally, please provide the complete runnable code in its entirety.”
Initially, there were some issues with the code generated by Amazon Q. However, after two interactive communication rounds, during which I provided clarifications and additional context, it finally outputted a runnable and optimized code.
The final revised code generated by the Amazon Q is shown in the following screenshot:
The final revised code generated by the Amazon Q
The final revised code generated by the Amazon Q
For your reference, I have provided the complete code optimized by Amazon Q Developer below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# The following code counts the number of S3 Buckets in a specified region, lists the names of the S3 Buckets in that region,
# and records the program's execution time.
#
# Revised by Amazon Q Developer
# Date: May 8, 2024

import time
from aws_cdk import (
App, Stack, CfnOutput
)
import boto3
from constructs import Construct

class MyStack(Stack):
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)

s3_client = boto3.client('s3', region_name='ap-east-1')
response = s3_client.list_buckets()
ap_east_1_buckets = []

for bucket in response['Buckets']:
bucket_region = s3_client.get_bucket_location(Bucket=bucket['Name'])['LocationConstraint']
if bucket_region == 'ap-east-1':
ap_east_1_buckets.append(bucket['Name'])

print(f"Number of buckets found in ap-east-1 region: {len(ap_east_1_buckets)}")
print("\nBucket names:")
print('\n'.join(ap_east_1_buckets))

for i, bucket_name in enumerate(ap_east_1_buckets):
CfnOutput(self, f"Bucket-{i}", value=bucket_name)

def main():
start_time = time.time()
app = App()
MyStack(app, "haowen-cdk-app-list-S3-demo")
app.synth()
end_time = time.time()
execution_time = end_time - start_time
print(f"\nTotal execution time: {execution_time} seconds")

if __name__ == "__main__":
main()
After running the above Python code, you will get the output as shown in the following screenshot:
The result of the revised code by Amazon Q Developer
The result of the revised code by Amazon Q Developer
We were delighted to see that after optimization by the Amazon Q Developer, the running time of the code was improved from the original 4.33 seconds to 1.7 seconds!
So how exactly did the Amazon Q Developer improve the code? To elaborate, before obtaining this optimized, runnable code, I had three rounds of interactive communication with Amazon Q. Due to space constraints, I will provide details on these three communication rounds in my next blog post.
----------------
However, I can still give curious developers a small spoiler. Let's take a look at the problems Amazon Q discovered in the program that affected execution efficiency. The issues with the legacy code identified by Amazon Q are listed below:
Regarding the code you provided, it appears to be a Python script that interacts with the AWS S3 service to list the S3 buckets in the 'ap-east-1' region and record the execution time of the script. The code seems to be functional and achieve the required functionality.
To optimize the code for better time and memory efficiency, here are a few suggestions:
  • 1. Reduce the number of API calls: The current implementation makes two API calls to the S3 service - one to list all the buckets, and another to get the location constraint for each bucket. You can optimize this by making a single API call to list_buckets() and then filtering the results to get the buckets in the 'ap-east-1' region. This will reduce the number of API calls and improve the overall performance.
  • 2. Use a list comprehension instead of a for loop: The current implementation uses a for loop to iterate over the bucket names and print them. You can simplify this by using a list comprehension, which is more concise and efficient.
  • 3. Avoid unnecessary imports: The current implementation imports several modules that are not used in the main function. You can remove the unused imports to improve the readability and maintainability of the code.
  • 4. Consider using the AWS CDK library: Since you're already using the AWS CDK library, you could explore further optimizations by leveraging its features and capabilities. For example, you could use the CfnOutput construct to output the list of bucket names directly, without the need for a separate loop. ……”

Summary

Amazon Q Developer, AWS's cutting-edge generative AI assistant tailored for the software development lifecycle, comprehends AWS architecture, resources, best practices, and documentation to provide contextual and actionable responses.
This blog post demonstrates leveraging Amazon Q Developer within Visual Studio Code to develop code for listing Amazon S3 buckets in a specific region. It covers writing the initial code with the assistance of the Amazon Q Developer Agent, comparing it to an existing inefficient "legacy" code, and subsequently optimizing that legacy code through Amazon Q Developer's guidance, resulting in a significant reduction in execution time.
As mentioned in the “Optimizing Legacy Code” section above, transforming legacy code into a high-performance version is not an instantaneous process. It took three rounds of detailed communication and interaction with Amazon Q before finally achieving the optimized code that met my expectations.
If you're interested in these three conversations and interactions, you can follow my next blog post. The communication and interaction process were indeed engaging and insightful, so stay tuned.
Note: The cover image for this blog post was generated by the Amazon Titan Image Generator G1 model on Amazon Bedrock.
 

Any opinions in this post are those of the individual author and may not reflect the opinions of AWS.

Comments