Home >Backend Development >Golang >How to Efficiently Chunk a Slice in Go?

How to Efficiently Chunk a Slice in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-12-28 10:10:11472browse

How to Efficiently Chunk a Slice in Go?

Slice Chunking in Go

As you have encountered, chunking a slice in Go can be achieved through the following steps:

  1. Determine the Chunk Size: Calculate the desired chunk size by dividing the length of the original slice by the number of CPUs you want to use.
  2. Iterate Over the Slice: Use a for loop to iterate over the original slice, starting from index 0.
  3. Create a New Slice: For each chunk, create a new slice to store the chunked elements.
  4. Append Chunks: Append the chunked elements to the new slice.
  5. Append to Divided Slice: Append the newly created slice to the divided slice, which will hold the final chunked slices.

Here's an updated example based on your code:

var divided [][]string

numCPU := runtime.NumCPU()
chunkSize := (len(logs) + numCPU - 1) / numCPU

for i := 0; i < len(logs); i += chunkSize {
    end := i + chunkSize

    if end > len(logs) {
        end = len(logs)
    }

    temp := logs[i:end]  // Create a new slice for the chunk
    divided = append(divided, temp)  // Append the chunk to the divided slice
}

The above is the detailed content of How to Efficiently Chunk a Slice in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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