Programming is about making decisions about how to implement any piece of code. Depending of such decisions, the code will be more or less readable, efficient, complex, etc. A common decision is also about to do it more or less idiomatic, that is, using specific statements or your programming language or paradigm.
As a proof of concept I have developed two code snippets, in Javascript, to analyze the performance. The goal is to generate a string in the form tagA|tagB|tagC
where then number of tagX
is random and the suffixes A
, B
, C
are random integers. Moreover, tagX
can not be repeated.
First implementation is more idiomatic, whereas the second one is more traditional. Next the code snippets of each one:
Idiomatic:
performance.mark('A');
let tags = new Set(Array.from({length: tagCount}, () => Math.floor(Math.random() * 10)));
tags = Array.from(tags).map(x => `tag${x}`).join('|');
performance.mark('B');
Traditional
performance.mark('C');
let tagset = new Set();
let tagstr = "";
for (let tag=0; tag<tagCount; tag++) {
tagset.add(Math.floor(Math.random() * 10));
}
tagset.forEach((tag) => {
tagstr += 'tag' + tag + '|'
});
tagstr = tagstr.slice(0, -1);
performance.mark('D');
To measure the performance I have used the Performance Timing API
The results are a bit surpraising, at least for me. Note how the traditional way is so much efficient than the other one.
Idiomatic: 0.436535
Traditional: 0.048177
I have repeated the experiment several times with similar results
Idiomatic way looks pretty cool and shorter, but it is less efficient and hard to read.
What do you think about it? Does it worth using idiomatic programming instead of traditional? Is there a general answer or it is strongly dependent of each case?
What about code readability and complexity?
EDITED: tagX
can not be repeated.
EDITED: just for reference, I have uploaded the complete code to Github: https://github.com/aecostas/benchmark-js-looping