Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Return number of characters in a Word

 
Raihan Jamal
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can we optimize this code more in a more efficient way?



 
Rob Spoor
Sheriff
Pie
Posts: 20665
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It would be more efficient to not split the String, but use one single loop over the entire String. Use a few variables to keep track of the current state; a new word is started when the previous character is whitespace etc, and a word ends when the current character is whitespace etc. It's a bit trickier to get it right, so perhaps you should keep your current version. If you can improve efficiency at the cost of readability (by yourself in the first place) then you shouldn't do it (unless you need the extra efficiency because your resources are limited).
 
Winston Gutkowski
Bartender
Pie
Posts: 10527
64
Eclipse IDE Hibernate Ubuntu
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Raihan Jamal wrote:Can we optimize this code more in a more efficient way?

I think, rather than worrying about the few nanoseconds you might save with a fully optimized piece of code, you should concentrate on the inconsistencies you have with your current one.

For example, your "letter counting" method uses the generic Character.isLetter(), but your split() only allows for English punctuation (and not all of that either).

Get the code right first. Then worry about efficiency.

And I'd say that the first step to getting it right is to write down, in English, exactly what you expect it to do.

Winston
 
fred rosenberger
lowercase baba
Bartender
Posts: 12196
35
Chrome Java Linux
  • Likes 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"more efficient" is not a well defined term. More efficient in terms of memory? speed? ease of understanding/refactoring?

just about everything in CS is a trade-off. faster execution may require more memory - a potential problem in mobile devices. Developers tend to spend more time fixing/correcting/debugging their code than anything else so writing code that is easy to understand usually saves more time.

Think about it...if you do something that saves a user a microsecond, then a million users will have to run that segment of code to save ONE SECOND.

However, if you write it in such a complicated way that it takes you eight hours to debug, test, package up, and distribute the patch, you have ended up 6 hours, 59 minutes and 59 seconds in the hole.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic