2

I have a method which should find a number of appearances of following words combination in array. This method is re-written in Java from C# code i've made but it performs 50 times slower which makes me think i don't know much in Java internals to properly translate it.

This is the Java code:

 private Map<String, Long> WeightWords(Map<Sentence, Long> wordsWithWeight) { Map<String, Long> newWordsWithWeight = new HashMap(); for (Map.Entry<Sentence, Long> item : wordsWithWeight.entrySet()) { String title = item.getKey().getTitle().toLowerCase(); String[] split = title.split("-"); String goodName = title.replace(split[0].trim() + " - ", ""); if (title.contains(split[0].trim() + " - ")) { goodName = title.replace(split[0].trim() + " - ", ""); } else if (title.contains(split[0].trim() + "- ")) { goodName = title.replace(split[0].trim() + "- ", ""); } String[] strings = goodName.split(" "); String fullString = ""; for (String s : strings) { if (!s.isEmpty()) { fullString += s + " "; String currentString = fullString.trim(); Long counter = 0L; for (Map.Entry<Sentence, Long> wordEntry : wordsWithWeight.entrySet()) { { if (wordEntry.getKey().getTitle().toLowerCase().trim().contains(currentString)) counter++; } } if (!newWordsWithWeight.containsKey(s)) newWordsWithWeight.put(s, counter); } } } return Utils.sortByValue(newWordsWithWeight); } 
3
  • You generate a lot of strings. Try to save title.replace(split[0].trim() + " - ", "")'s and similar results, since it will generation new string each time. Commented Dec 16, 2014 at 10:10
  • Also, in the loop, replace fullString += s + " "; with appending to a StringBuilder. Commented Dec 16, 2014 at 10:18
  • Thanks guys the list is quite small 1000 records max so i never though string performance will be so awful. Commented Dec 16, 2014 at 10:20

2 Answers 2

1

In your code you run n*n on same entry set named 'wordsWithWeight', and on each iteration you call toLowerCase() and trim(). You can prepare your entry set before and then remove toLowerCase() and trim() calls on each iteration.This should increase performance.

Sign up to request clarification or add additional context in comments.

Comments

1

You are using a lot of Strings. Try to use StringBuffer or StringBuilder instead. Especially when you concatenate a lot you'll need them. Here's a link with more details: Read me

2 Comments

Collection are way too small to cause such thing and i don't see where i can use StringBuffer at all to be honest.
@ fullString for example ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.