The fastest and preferred way to do string concatenation under Arduino is,
- Use the String class.
- If you really need the speed and/or simply want to avoid creating new in-memory strings with every concatenation operation, reserve the needed memory ahead of time with reserve().
- First, set the object to an empty string "".
- Then, append the needed characters or strings by invoking concat() or the operator +=, using exactly one concat() or += operation per line of code. This is to avoid the creation of temporary Strings objects.
- By executing reserve() in advance, the String object will be effectively acting as a line buffer.
By applying the above guidelines, the concatenation operations will be done in place.
Note that reserve() should be called with the most appropriate value for the line buffer capacity, i.e.: maximum number of characters you need before String does a realloc(), not including the null-terminating character '\0'.
Three alternatives follow:
1) Here is the sample code,
// Declaration, outside setup() and loop()
String line;
// Inside setup()
// Use the appropriate value for reserve(), depending on on your actual usage.
line.reserve(10);
// Inside loop()
line = "";
line += minutes;
line += ":";
line += seconds;
line += ":";
line += m;
Serial.println(line);
2) As an alternative to calling reserve() at setup(), you could declare and initialize the String with a "template" or dummy string which has the desired (maximum) length.
Here is the sample code for this alternative,
// Declaration, outside setup() and loop()
String line = "XXXX:YY:ZZ";
// No need to use reserve() inside setup()
// Inside loop()
line = "";
line += minutes;
line += ":";
line += seconds;
line += ":";
line += m;
Serial.println(line);
The first approach allows you to use reserve() with a dynamically calculated maximum length value, while the second approach results in somewhat cleaner to read code when you have a "template" or known fixed length for the string you will be later composing.
3) If you only need to output the data to the output stream (usually Serial), this is the fastest and the most compact code, with no need of String or external libraries,
// No need to declare a String outside setup() and loop()
// No need to use reserve() inside setup()
// Inside loop()
Serial.print(minutes);
Serial.print(":");
Serial.print(seconds);
Serial.print(":");
Serial.println(m);
Note: the answer by John Y does exactly the same as my last piece of code, except for his "simpler" to read code (assuming you feel comfortable with the operator <<, used as C++ streaming syntactic sugar). In some cases, however, using the Streaming library will generate slightly larger/slower code.