Home Backend Development Golang How to optimize the performance of large number of image link replacements using Golang?

How to optimize the performance of large number of image link replacements using Golang?

Apr 02, 2025 pm 12:12 PM
git golang access ai

How to optimize the performance of large number of image link replacements using Golang?

This article discusses how to optimize Golang code and efficiently handle large-scale image link replacement, especially for scenarios where images are uploaded to Alibaba Cloud OSS and replaced the original link. Performance bottlenecks are often frequent network requests and resource creation.

Assume that the initial string contains multiple image links:

 <code>content := `<img  class="wscnph lazy" src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/001/246/273/174278558460021.jpg" alt="How to optimize the performance of large number of image link replacements using Golang?" ><img  class="wscnph lazy" src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/001/246/273/174278558769141.jpg" alt="How to optimize the performance of large number of image link replacements using Golang?" > `</code>
Copy after login

We need to match the link, upload it to OSS, and replace the original link. The original code has performance problems, which are mainly reflected in the repeated creation of OSS clients and blocking uploads.

For optimization, we will adopt the following strategies:

  1. Singleton OSS client: Use sync.Once to ensure that oss.New is executed only once, avoiding repeated creation of OSS client instances.

  2. Concurrent upload: Use goroutine to upload images concurrently to OSS to avoid blocking the main thread.

  3. Caching mechanism (optional): Introduce caches (such as sync.Map ) to store old and new link mappings of uploaded images to avoid repeated uploads of the same images.

The improved code is as follows:

 package main

import (
    "bytes"
    "fmt"
    "regexp"
    "strconv"
    "strings"
    "sync"
    "time"

    "github.com/aliyun/aliyun-oss-go-sdk/oss"
)

// ... (Aliyun OSS configuration: Endpoint, key, AccessKeySecret, BucketName) ...

var (
    ossClient *oss.Client
    once sync.Once
    imgCache sync.Map // key: old URL, value: new URL
)

func getOSSClient() *oss.Client {
    once.Do(func() {
        client, err := oss.New(Endpoint, key, AccessKeySecret)
        if err != nil {
            panic(err) // Handle error appropriately in production
        }
        ossClient = client
    })
    return ossClient
}


func Upload(url string) (string, error) {
    client := getOSSClient()
    bucket, err := client.Bucket(BucketName)
    if err != nil {
        return "", err
    }

    t1 := time.Now().Unix()
    long := 0 // Simplified counter, consider a more robust solution
    obj := fmt.Sprintf("article/%d%d.png", t1, long)

    err = bucket.PutObject(obj, bytes.NewReader(ReadImgData(url))) // ReadImgData function assumed to exist
    if err != nil {
        return "", err
    }
    return "https://" BucketName "." Endpoint "/" obj, nil
}

func RepImages(htmls string) string {
    var imgRE = regexp.MustCompile(`<img  alt="How to optimize the performance of large number of image link replacements using Golang?" > ]*src=["']([^"'] )["'][^>]*>`) // Improved regex
    imgs := imgRE.FindAllStringSubmatch(htmls, -1)
    var wg sync.WaitGroup
    resultChan := make(chan string, len(imgs))

    for _, img := range imgs {
        if len(img) > 1 {
            oldURL := img[1]
            if newURL, ok := imgCache.Load(oldURL); ok {
                resultChan <img  class="wscnph lazy" src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/001/246/273/174278558769141.jpg" alt="How to optimize the performance of large number of image link replacements using Golang?" > `
    fmt.Println(RepImages(content))
}

// Placeholder for the actual image reading function
func ReadImgData(url string) []byte {
    // Replace this with your actual image reading logic
    // ...
    return []byte("image data")
}
Copy after login

Remember to replace Endpoint , key , AccessKeySecret , and BucketName for your Alibaba Cloud OSS configuration. ReadImgData function needs to be implemented according to your actual situation. This improved version utilizes concurrency and caching, significantly improving the efficiency of handling large number of image links. Error handling has also been strengthened to avoid program crashes. The caching mechanism can be further optimized, such as using LRU caching policies to manage memory usage.

The above is the detailed content of How to optimize the performance of large number of image link replacements using Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to delete a repository by git How to delete a repository by git Apr 17, 2025 pm 04:03 PM

To delete a Git repository, follow these steps: Confirm the repository you want to delete. Local deletion of repository: Use the rm -rf command to delete its folder. Remotely delete a warehouse: Navigate to the warehouse settings, find the "Delete Warehouse" option, and confirm the operation.

How to use git commit How to use git commit Apr 17, 2025 pm 03:57 PM

Git Commit is a command that records file changes to a Git repository to save a snapshot of the current state of the project. How to use it is as follows: Add changes to the temporary storage area Write a concise and informative submission message to save and exit the submission message to complete the submission optionally: Add a signature for the submission Use git log to view the submission content

How to solve the efficient search problem in PHP projects? Typesense helps you achieve it! How to solve the efficient search problem in PHP projects? Typesense helps you achieve it! Apr 17, 2025 pm 08:15 PM

When developing an e-commerce website, I encountered a difficult problem: How to achieve efficient search functions in large amounts of product data? Traditional database searches are inefficient and have poor user experience. After some research, I discovered the search engine Typesense and solved this problem through its official PHP client typesense/typesense-php, which greatly improved the search performance.

How to use git rebase How to use git rebase Apr 17, 2025 pm 04:00 PM

git rebase is used to reapply commits to a new baseline to clean up history or relocate branches. How to use: Create a target branch Select the commit to be reapplied and execute the git rebase command, specify the target branch and commit scope to resolve conflicts, continue to reapply the remaining commit verification changes.

How to download git projects to local How to download git projects to local Apr 17, 2025 pm 04:36 PM

To download projects locally via Git, follow these steps: Install Git. Navigate to the project directory. cloning the remote repository using the following command: git clone https://github.com/username/repository-name.git

What to do if the git download is not active What to do if the git download is not active Apr 17, 2025 pm 04:54 PM

Resolve: When Git download speed is slow, you can take the following steps: Check the network connection and try to switch the connection method. Optimize Git configuration: Increase the POST buffer size (git config --global http.postBuffer 524288000), and reduce the low-speed limit (git config --global http.lowSpeedLimit 1000). Use a Git proxy (such as git-proxy or git-lfs-proxy). Try using a different Git client (such as Sourcetree or Github Desktop). Check for fire protection

How to solve the complexity of WordPress installation and update using Composer How to solve the complexity of WordPress installation and update using Composer Apr 17, 2025 pm 10:54 PM

When managing WordPress websites, you often encounter complex operations such as installation, update, and multi-site conversion. These operations are not only time-consuming, but also prone to errors, causing the website to be paralyzed. Combining the WP-CLI core command with Composer can greatly simplify these tasks, improve efficiency and reliability. This article will introduce how to use Composer to solve these problems and improve the convenience of WordPress management.

How to submit empty folders in git How to submit empty folders in git Apr 17, 2025 pm 04:09 PM

To submit an empty folder in Git, just follow the following steps: 1. Create an empty folder; 2. Add the folder to the staging area; 3. Submit changes and enter a commit message; 4. (Optional) Push the changes to the remote repository. Note: The name of an empty folder cannot start with . If the folder already exists, you need to use git add --force to add.

See all articles