• Latest
Batch Processing in Go – DZone Web Dev

Batch Processing in Go – DZone Web Dev

January 5, 2022
SteamOS 3.2 update adds refresh rate settings, quieter fan curve to the Steam Deck

SteamOS 3.2 update adds refresh rate settings, quieter fan curve to the Steam Deck

May 27, 2022
Cyberpunk 2077: PS5 and Xbox Series X/S Versions Are Out Now

Cyberpunk 2077 Expansion: Leak Points to Inaccessible Areas Being Opened

May 27, 2022
Nintendo Download: 27th May (Europe)

Nintendo Download: 27th May (Europe)

May 27, 2022
Minecraft’s The Wild update confirmed for June

Minecraft’s The Wild update confirmed for June

May 27, 2022
A solid option for Fuji!

A solid option for Fuji!

May 27, 2022
Honor shares details about the Magic4 Pro R&D process

Honor shares details about the Magic4 Pro R&D process

May 27, 2022
Xbox boss will “absolutely support” Raven Software’s new union

Xbox boss will “absolutely support” Raven Software’s new union

May 27, 2022
Pro Darts 2022+ Is Out Now on Apple Arcade Alongside Big Updates for Dear Reader, Crayola Create and Play+, Sonic Dash+, and Cut the Rope Remastered – TouchArcade

Pro Darts 2022+ Is Out Now on Apple Arcade Alongside Big Updates for Dear Reader, Crayola Create and Play+, Sonic Dash+, and Cut the Rope Remastered – TouchArcade

May 27, 2022
The Callisto Protocol distances itself from PUBG

The Callisto Protocol distances itself from PUBG

May 27, 2022
Realme unveils 512GB version of the GT Neo3, offers discounts for China’s 618 shopping festival

Realme unveils 512GB version of the GT Neo3, offers discounts for China’s 618 shopping festival

May 27, 2022
All TV shows and movies streaming on Apple TV

All Apple TV shows and movies

May 27, 2022
Random: Yes, This Really Is A Working Cardboard Game Boy Advance SP

Random: Yes, This Really Is A Working Cardboard Game Boy Advance SP

May 27, 2022
Advertise with us
Friday, May 27, 2022
Bookmarks
  • Login
  • Register
GetUpdated
  • Home
  • Game Updates
    • Mobile Gaming
    • Playstation News
    • Xbox News
    • Switch News
    • MMORPG
    • Game News
    • IGN
    • Retro Gaming
  • Tech News
    • Apple Updates
    • Jailbreak News
    • Mobile News
  • Software Development
  • Photography
  • Contact
    • Advertise With Us
    • About
No Result
View All Result
GetUpdated
No Result
View All Result
GetUpdated
No Result
View All Result
ADVERTISEMENT

Batch Processing in Go – DZone Web Dev

January 5, 2022
in Software Development
Reading Time:3 mins read
0 0
0
Share on FacebookShare on WhatsAppShare on Twitter


Batching is a common scenario developers come across to basically split a large amount of work into smaller chunks for optimal processing. Seems pretty simple, and it really is. Say we have a long list of items we want to process in some way. A pre-defined number of them can be processed concurrently. I can see two different ways to do it in Go.

The first way is by using plain old slices. This is something most developers have probably done at some point in their careers. Let’s take this simple example:

func main() {
	data := make([]int, 0, 100)
	for n := 0; n < 100; n++ {
		data = append(data, n)
	}
	process(data)
}

func processBatch(list []int) {
	var wg sync.WaitGroup
	for _, i := range list {
		x := i
		wg.Add(1)
		go func() {
			defer wg.Done()
			// do more complex things here
			fmt.Println(x)
		}()
	}
	wg.Wait()
}

const batchSize = 10

func process(data []int) {
	for start, end := 0, 0; start <= len(data)-1; start = end {
		end = start + batchSize
		if end > len(data) {
			end = len(data)
		}
		batch := data[start:end]
		processBatch(batch)
	}
	fmt.Println("done processing all data")
}

The data to process is a plain list of integers. To keep things simple, we just want to print all of them,10 concurrently at most. To achieve this, we loop over the list, divide it into chunks of batchSize = 10, and process each batch serially. Short and sweet, and does what we want.

The second approach uses a buffered channel, similar to what’s described in this post on concurrency. Let’s look at the code first.

func main() {
	data := make([]int, 0, 100)
	for n := 0; n < 100; n++ {
		data = append(data, n)
	}
	batch(data)
}

const batchSize = 10

func batch(data []int) {
	ch := make(chan struct{}, batchSize)
	var wg sync.WaitGroup
	for _, i := range data {
		wg.Add(1)
		ch <- struct{}{}
		x := i
		go func() {
			defer wg.Done()
			// do more complex things here
			fmt.Println(x)
			<-ch
		}()
	}
	wg.Wait()
	fmt.Println("done processing all data")
}

This example uses a buffered channel of size 10. As each item is ready to be processed, it tries to send to the channel. Sends are blocked after 10 items. Once processed, it reads from the channel, thereby releasing from the buffer. Using a struct{}{} saves us some space, because whatever is sent to the channel never gets used.

As the author of the post points out, here we’re exploiting the properties of a buffered channel to limit concurrency. One might argue this is not really batching, but rather it’s concurrent processing with a threshold. I would totally agree. Regardless, it gets the job done and the code is a tad simpler.

Is it any better than slices? Probably not. As for speed, I timed the execution of both programs, and they ran pretty close. These examples are far too simple to see any significant difference in runtime. Channels in general are slower and more expensive than slices. Since there is no meaningful data being passed between the goroutines, it’s probably a wasted effort. So why would I do it this way? Well, I like simple code, but that might not be enough of a reason. If the cost of serial processing of each batch outweighs the cost of using a channel, it might be worth consideration!



Source link

ShareSendTweet
Previous Post

Ahead of Apple Headset launch, Meta reportedly halts efforts to build its own AR/VR OS

Next Post

Arcadia Fallen Is A Visual Novel With A Heavy Focus On Roleplay, And It’s Out Today

Related Posts

Android App to Monitor Hudson – Part II Configurations

May 27, 2022
0
0
Android App to Monitor Hudson – Part II Configurations
Software Development

Last week, demonstrated building and Android application that queried Hudson remote api through REST calls, which returned back JSON objects;...

Read more

Announcing the JavaFXpert RIA Exemplar Challenge

May 27, 2022
0
0
Announcing the JavaFXpert RIA Exemplar Challenge
Software Development

I posed the question "Should There be Enterprise RIA Style Guidelines?" on JavaLobby in late 2008, and received some valuable...

Read more
Next Post
Arcadia Fallen Is A Visual Novel With A Heavy Focus On Roleplay, And It’s Out Today

Arcadia Fallen Is A Visual Novel With A Heavy Focus On Roleplay, And It's Out Today

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

© 2021 GetUpdated – MW.

  • About
  • Advertise
  • Privacy & Policy
  • Terms & Conditions
  • Contact

No Result
View All Result
  • Home
  • Game Updates
    • Mobile Gaming
    • Playstation News
    • Xbox News
    • Switch News
    • MMORPG
    • Game News
    • IGN
    • Retro Gaming
  • Tech News
    • Apple Updates
    • Jailbreak News
    • Mobile News
  • Software Development
  • Photography
  • Contact
    • Advertise With Us
    • About

Welcome Back!

Login to your account below

Forgotten Password? Sign Up

Create New Account!

Fill the forms bellow to register

All fields are required. Log In

Retrieve your password

Please enter your username or email address to reset your password.

Log In
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?