Saturday, September 27, 2025
HomeGolangSync.As soon as vs Singleton Initialisation - Technical Dialogue

Sync.As soon as vs Singleton Initialisation – Technical Dialogue


I’ve to get a single occasion of DB. For this I wrote the next code –

func getDb() map[string]int {
	if db == nil {
		lock.Lock()
		if db == nil {
			db = map[string]int{}
		}
		lock.Unlock()
	}
	return db
}

There may be one other method to do that utilizing Sync.As soon as –

func (o *As soon as) Do(f func()) {
	if atomic.LoadUint32(&o.accomplished) == 0 {
		o.doSlow(f)
	}
}
func (o *As soon as) doSlow(f func()) {
	o.m.Lock()
	defer o.m.Unlock()
	if o.accomplished == 0 {
		defer atomic.StoreUint32(&o.accomplished, 1)
		f()
	}
}

Which one ought to I exploit ?
Is the
atomic.LoadUint32(&o.accomplished) == 0 computationally costly than db == nil ?

the 2 examples will not be doing the identical factor. As soon as is a prepared to make use of answer whereas the primary instance is handmade. if need to do a number of occasions …perhaps higher As soon as

However, the benchmark instrument suggests in any other case –

properly, if to your use case 130ns are crucial … use the primary answer, in any other case I choose to make use of “ready-to-use” answer; but it surely’s simply my thought

Hello @Harshit_Soni ,

Use sync.As soon as to create singletons, that’s the idiomatic Golang method.

Why do you care how briskly is that this trivial and barely used operation ? You often solely must create a connection to DB solely as soon as in your software, why do you care if it takes 10% longer ? If a code is simpler to learn (preserve) it’s often value to decide on the more serious algorithm.

Your benchmark reveals solely a really small distinction, and should even present the other in the event you run it for an extended time. Looks like a straightforward option to go for sync.As soon as

Proper. If I’m not mistaken, we’re speaking about 0.00000013 seconds on an operation that, by definition, goes to be carried out solely as soon as. Relying on the use case, this may additionally be an excellent candidate for an init perform. That method you possibly can take concurrency out of the image utterly and this db property is simply there when your app begins.

Atomics are low-level reminiscence primitives and are fairly performant based mostly on my utilization/understanding of them. I’m questioning if that very slight efficiency hole is attributable to the defer o.m.Unlock()? Additionally maybe there’s very slight overhead from having a number of capabilities / a closure. Both method, it doesn’t matter as a result of I can assure you that connecting to your database and authenticating goes to take orders of magnitude longer than any efficiency hit you may incur by utilizing sync.As soon as.

Thanks quite a bit everybody,
received my reply. :smile:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments