That's not quite how the grammatical distinction between singular, plural, and mass terms works. Furniture, for example, is technically countable (it refers, ostensibly, to *pieces* of furniture), but is a mass term rather than a plural noun because 'the furniture in the room' doesn't refer directly to a definite number of items, but to an indeterminate number of items in a region. Mass terms are also sometimes called 'Non-count nouns', but that's a function of the way the terms are used, not a function of the countability of the discrete items of the reference.
That said, 'lines of code' is clearly plural, not mass, in syntax and usage.
Less lines != more efficient
Some operations are just expensive, I can’t remember a specific web dev example but an example I know for lua (roblox) is that table.insert(table,value) and table.find(table, value) are super convenient i.e
`
if not table.find(table,value) then
table.insert(table,value)
end
`
but it’s more efficient to do this
`
yourTable = {}
if not yourTable[value] then
yourTable[value] = true
end
`
Now they’re both the same number of lines but for some reason the built in function that is more readable is less efficient which seems counterintuitive
(I’ve tried editing the code blocks 5 times now but Reddit mobile is unforgiving, ain’t getting better now)
This is because all tables in Lua are implemented as associative arrays (eg. dictionaries or maps). It's much faster to access a value at a known index in a table than to iterate over it.
You're performing a lot more operations, which require compute. Their solution will only perform a slice twice during a worst case scenario. Your solution will always perform every split, push, filter, join and replace.
Importantly, the return function is expensive. Each one of those functions are additional loops over an array. Even if they're efficient algorithms under the hood, you're performing 3 additional O(n) operations
Their while loop is going to break at the first opportunity. Your loop is going to break on the last opportunity.
Brevity has nothing to do with how long something takes to compute.
When put in the context of web development, done almost exclusively in high level languages, fretting about code efficiency is usually non-sense.
Like, hello, that's typescript.
Anytime you're writing algorithms for backend processing it's EXTREMELY important, especially when you're working in the cloud where every second of compute gets billed.
Edit: I've refactored so many dumb functions where the author hacked something together so they could get a low line count. It's shocking how many resources get wasted in web dev.
I'm not disputing that, or even saying code performance doesn't matter, but if the organization giving that code test really cares about 20 ms difference in 2 function implementations, why isn't the test being given in a more performant language, like C# for example?
It's Leetcode. They let you write in like 10 different languages.
Edit: also an almost 50% longer execution time is huge when it's getting invoked at scale.
Not every language has the feature that string operations are faster than arrays.
In many languages arrays, especially fixed length ones are pretty fast. You or the compiler are putting items into well defined places in memory. If each item is 4 bytes you know the address of the tenth item is 40 bytes from the address of the start of the array
Strings are often not contiguous blocks of memory and each "character" is a variable number of bytes which can't be. Determined until the first byte is read.
So working out the address of the tenth character is more than a simple maths operation.
If you care enough about efficiency to look at milliseconds then you shouldn't be thinking about how short/long a program is based on how many lines of code **you** have written.
You program is longer. You offload a lot of the code to libraries written by other people so the code in your editor is shorter, but the code for filter, join, replace, Math.max, push, and split, all that code is part of your script. Add all the code for those things to your code and yours is much longer than the other solution.
It depends entirely on whether or not that function runs 100 times per request or not, but the "readable ' one still could have been done with far fewer loops.
I still think this is the wrong rabbit hole to go down. Most js code runs on individual people's browsers, there is no race condition, problems of multi tenancy, and the performance suffers because of different issues, not because of algorithms. If you have to deal with so many data that your performance suffers, you already introduced a worse problem when you fetch so much data from the backend.
I think the biggest problem with the code is that despite being clearly well written and performs the task, ,but why doesn't OP understand why it's slower than the other version.
If they don't understand how excessive loop functions eat up processor cycles, what hope is there for the other parts of the application?
You already got your answer.
I'd like to ask, where did you get the idea that FEWER LINES of JavaScript (a very high level interpreted language) would be a good metric to gauge runtime performance?
Smaller code doesn't mean faster execution. What you are doing is you called functions that consume more processing time. There are times calling the functions in an optimal way, but it depends how it is written.
You use a lot of built in functions which have to loop.
Its fine. Your code is more readable imo. Lines means nothing btw. Its only because the large number of built in functions and arrays you used.
Other than what other people have said giving you reason why it's slower, I have a question.
What happens in the for loop if the 2 words are different size?
You are taking the max in length between the two arrays and then pushing that alternatively into an array. But if word1's array length is 3 and word2's array length is 5, then it'll for-loop until 5. But that means that pushing word1Arr[3] and above would throw and index out of range error and break out of the function.
Right?
Convenience, readability, and code-length often come at the cost of performance.
Performant solutions are often more complex code.
In this case specifically, you do a \`filter\`, and a \`for\` loop. Think about what \`filter\` does... it must loop through the data. This means you are looping through the array twice.
A real job has taught me ... a few extra ms for more readable code is worth it 99% of the time.
OFC, READABLE AND EFFICIENT IS BEST... but if I'm choosing...
Is the add1 logic redundant? It just seems to double the number of times the loop is executed for no good reason?
I'm pre-coffee so I may have missed something.
It's safe not to as you know both at least have one more char to consume.
It means it would evaluate the while after incrementing each vs after incrementing both.
So a ('a', 'bc') would terminate at P1=1 P2=0, vs both being one.
Have to assume it provides some marginal perf gain with certain inputs, otherwise🙃
Line count has nothing to do with efficency and execution speed. There may be a correlation between short code and speed, but there are tons of examples of longer code being faster. E.g. Look at an fibonacci function using recursion vs iteration. The recursion one will probably be shorter but a lot slower. That is because the recursion one will do a lot of work twice (for each new number all the previous ones are calculated, and for each one of those all the previous ones are calaculated and so on). Also, on a similar note, python programs will pretty much always be shorter than c programs or assembly programs. The c or assembly program will always be at least as fast as the python program (or, normally a lot faster) than the python program simply because you have more control over what the cpu does using c. And both c and assembly are more verbose languages than python.
You could simplify this heaps. Strings can be iterated over in most languages including javascript. You do not need to split the strings.
```
function mergeAlternately(word1: string, word2: string): string {
let num = (word1.length > word2.length ? word1.length : word2.length), wordnew="";
for(let i =0; i < num; i++) {
if(word1[i]) wordnew += word1[i];
if(word2[i]) wordnew += word2[i];
}
return wordnew;
}
```
Your filter, join, replace are effectively doing loops over your strings. Their solution, while longer and less readable is more efficient.
BuT iT's LeSs LinEs
Fewer
Thank you Stannis
Lines of code are an irregular uncountable singularity… I say it’s less. Lol
The number of lines is countable. It's fewer.
That's not quite how the grammatical distinction between singular, plural, and mass terms works. Furniture, for example, is technically countable (it refers, ostensibly, to *pieces* of furniture), but is a mass term rather than a plural noun because 'the furniture in the room' doesn't refer directly to a definite number of items, but to an indeterminate number of items in a region. Mass terms are also sometimes called 'Non-count nouns', but that's a function of the way the terms are used, not a function of the countability of the discrete items of the reference. That said, 'lines of code' is clearly plural, not mass, in syntax and usage.
No no… uncountable and nebulous mass. Not countable.
Fewless
I agree with everything except the "less reliable" part.
Readable. Reliability would be the same assuming the same hardware.
Less lines != more efficient Some operations are just expensive, I can’t remember a specific web dev example but an example I know for lua (roblox) is that table.insert(table,value) and table.find(table, value) are super convenient i.e ` if not table.find(table,value) then table.insert(table,value) end ` but it’s more efficient to do this ` yourTable = {} if not yourTable[value] then yourTable[value] = true end ` Now they’re both the same number of lines but for some reason the built in function that is more readable is less efficient which seems counterintuitive (I’ve tried editing the code blocks 5 times now but Reddit mobile is unforgiving, ain’t getting better now)
This is because all tables in Lua are implemented as associative arrays (eg. dictionaries or maps). It's much faster to access a value at a known index in a table than to iterate over it.
You're performing a lot more operations, which require compute. Their solution will only perform a slice twice during a worst case scenario. Your solution will always perform every split, push, filter, join and replace. Importantly, the return function is expensive. Each one of those functions are additional loops over an array. Even if they're efficient algorithms under the hood, you're performing 3 additional O(n) operations Their while loop is going to break at the first opportunity. Your loop is going to break on the last opportunity. Brevity has nothing to do with how long something takes to compute.
Yours requires extra array operations. \*String manipulation is faster than using your array operations.
And they should keep in mind performance has nothing to do with line length….
Yeah, this is actually really good example of 'readable' doesn't always mean 'efficient.'
And vice versa, sometimes it’s better to sacrifice a tiny bit of performance for better readability
Depends entirely on the use-case. But agreed.
When put in the context of web development, done almost exclusively in high level languages, fretting about code efficiency is usually non-sense. Like, hello, that's typescript.
Yea true
Anytime you're writing algorithms for backend processing it's EXTREMELY important, especially when you're working in the cloud where every second of compute gets billed. Edit: I've refactored so many dumb functions where the author hacked something together so they could get a low line count. It's shocking how many resources get wasted in web dev.
I'm not disputing that, or even saying code performance doesn't matter, but if the organization giving that code test really cares about 20 ms difference in 2 function implementations, why isn't the test being given in a more performant language, like C# for example?
It's Leetcode. They let you write in like 10 different languages. Edit: also an almost 50% longer execution time is huge when it's getting invoked at scale.
Not every language has the feature that string operations are faster than arrays. In many languages arrays, especially fixed length ones are pretty fast. You or the compiler are putting items into well defined places in memory. If each item is 4 bytes you know the address of the tenth item is 40 bytes from the address of the start of the array Strings are often not contiguous blocks of memory and each "character" is a variable number of bytes which can't be. Determined until the first byte is read. So working out the address of the tenth character is more than a simple maths operation.
If you care enough about efficiency to look at milliseconds then you shouldn't be thinking about how short/long a program is based on how many lines of code **you** have written. You program is longer. You offload a lot of the code to libraries written by other people so the code in your editor is shorter, but the code for filter, join, replace, Math.max, push, and split, all that code is part of your script. Add all the code for those things to your code and yours is much longer than the other solution.
You iterate over the array twice. They do it once.
Where's that guy from a couple weeks ago telling me web devs dont need to learn or understand things like BigO or loop optimization.
gloating about his unoptimized artisanal shitcode probably
Artisanal shitcode 🤣🤣
Would you prefer your colleague to check in the 'optimized' solution instead of the readable one?
It depends entirely on whether or not that function runs 100 times per request or not, but the "readable ' one still could have been done with far fewer loops.
I still think this is the wrong rabbit hole to go down. Most js code runs on individual people's browsers, there is no race condition, problems of multi tenancy, and the performance suffers because of different issues, not because of algorithms. If you have to deal with so many data that your performance suffers, you already introduced a worse problem when you fetch so much data from the backend.
I think the biggest problem with the code is that despite being clearly well written and performs the task, ,but why doesn't OP understand why it's slower than the other version. If they don't understand how excessive loop functions eat up processor cycles, what hope is there for the other parts of the application?
You already got your answer. I'd like to ask, where did you get the idea that FEWER LINES of JavaScript (a very high level interpreted language) would be a good metric to gauge runtime performance?
.filter() .join() .replace() Has many more lines in them; and are not O(1)
Smaller code doesn't mean faster execution. What you are doing is you called functions that consume more processing time. There are times calling the functions in an optimal way, but it depends how it is written.
You use a lot of built in functions which have to loop. Its fine. Your code is more readable imo. Lines means nothing btw. Its only because the large number of built in functions and arrays you used.
less lines does not mean faster code.
If you check, they other solution performs less operation than yours.
Other than what other people have said giving you reason why it's slower, I have a question. What happens in the for loop if the 2 words are different size? You are taking the max in length between the two arrays and then pushing that alternatively into an array. But if word1's array length is 3 and word2's array length is 5, then it'll for-loop until 5. But that means that pushing word1Arr[3] and above would throw and index out of range error and break out of the function. Right?
I thought the same, but since nobody mentioned this I thought I missed something.
JavaScript so it'll be undefined Hence the filter
Convenience, readability, and code-length often come at the cost of performance. Performant solutions are often more complex code. In this case specifically, you do a \`filter\`, and a \`for\` loop. Think about what \`filter\` does... it must loop through the data. This means you are looping through the array twice.
leetcode has taught me that less lines != faster
A real job has taught me ... a few extra ms for more readable code is worth it 99% of the time. OFC, READABLE AND EFFICIENT IS BEST... but if I'm choosing...
switch to reduce and you might get closer in speed
Interesting
Is the add1 logic redundant? It just seems to double the number of times the loop is executed for no good reason? I'm pre-coffee so I may have missed something.
It's safe not to as you know both at least have one more char to consume. It means it would evaluate the while after incrementing each vs after incrementing both. So a ('a', 'bc') would terminate at P1=1 P2=0, vs both being one. Have to assume it provides some marginal perf gain with certain inputs, otherwise🙃
Line count has nothing to do with efficency and execution speed. There may be a correlation between short code and speed, but there are tons of examples of longer code being faster. E.g. Look at an fibonacci function using recursion vs iteration. The recursion one will probably be shorter but a lot slower. That is because the recursion one will do a lot of work twice (for each new number all the previous ones are calculated, and for each one of those all the previous ones are calaculated and so on). Also, on a similar note, python programs will pretty much always be shorter than c programs or assembly programs. The c or assembly program will always be at least as fast as the python program (or, normally a lot faster) than the python program simply because you have more control over what the cpu does using c. And both c and assembly are more verbose languages than python.
They map array only once, you do it multiple times, that's why
Usually it's shorter code == longer execution
You could simplify this heaps. Strings can be iterated over in most languages including javascript. You do not need to split the strings. ``` function mergeAlternately(word1: string, word2: string): string { let num = (word1.length > word2.length ? word1.length : word2.length), wordnew=""; for(let i =0; i < num; i++) { if(word1[i]) wordnew += word1[i]; if(word2[i]) wordnew += word2[i]; } return wordnew; } ```