I made a single function for smoothed values, but is this code bad practice?

As I beginner I often feel like I’m doing something wrong. Today I coded 2 functions that basically “automate” the process of having to repeat code and create new variables for smoothing variables, it works but is this code bad/slow? And what parts of it is and how can I fix it?

float smoothLinear(AudioParameterFloat* paramPtr, float speed = 0.05) {
	static std::map<String, float> smoothedVars;
	float& smoothedVar = smoothedVars[paramPtr->paramID];
	if (abs(smoothedVar - paramPtr->get()) >= speed) {
		smoothedVar = smoothedVar - speed * (smoothedVar - paramPtr->get());
	}
	return smoothedVar;
}
float smoothExp(AudioParameterFloat* paramPtr, float speed = 0.05) {
	static std::map<String, float> smoothedVars;
	float& smoothedVar = smoothedVars[paramPtr->paramID];
	if (abs(smoothedVar - paramPtr->get()) >= speed) {
		if (smoothedVar == 0) {
			smoothedVar = paramPtr->get();
		}
		else {
			smoothedVar *= exp((log(paramPtr->get()) - log(smoothedVar)) * speed);
		}
	}
	return smoothedVar;
}

Here’s an example of how I use this code:
A pointer to a parameter I have is mMixParameter and I want a smoothed value for it, all I do is: float mixSmoothed = smoothedLinear(mMixParameter)

You don’t want to be using static variables like that in a plugin. It will blow up when you have multiple instances of your plugin running in a multithreading host. (Possibly there are other issues too…) Static and global variables are shared between all the plugin instances running in the same process.

I would also think that is going to be quite slow since it needs to be doing the lookups into the map for each sample etc.

Your code can’t really be fixed, unfortunately. You need to solve the parameter value smoothing problem in some other way with a class. You would then have an instance of that class for each parameter that needs the smoothing. Juce already has the value smoother classes like LinearSmoothedValue.

1 Like

Thanks for the feedback!
I looked at the linearSmoothedValue class but I’m a bit confused at how it works. Do you have any examples for how it’s used with a parameter?

Rail

1 Like

Thank you!