Results 1 to 4 of 4
Thread: Code architecture
- 01-27-2012, 07:59 PM #1
Senior Member
- Join Date
- Jan 2012
- Posts
- 210
- Rep Power
- 2
Code architecture
Have four different code examples with same output result.
Question is, which example is better?
or:Java Code:public static void main (String[] args) { String prefix = prefix("xxx00", "xxxxxxxxxx"); } public static String prefix(String s1, String s2) { int min = s1.length() < s2.length() ? s1.length() : s2.length(); String prefix = ""; int i = 0; while (i < min && s1.charAt(i) == s2.charAt(i)) { prefix += s1.charAt(i++); } return prefix; }
or:Java Code:while (i < min) { if (s1.charAt(i) == s2.charAt(i)) prefix += s1.charAt(i); i++; }
or:Java Code:for (int i = 0; i < min; i++) if (s1.charAt(i) == s2.charAt(i)) prefix += s1.charAt(i);
or?Java Code:for (int i = 0; i < min && s1.charAt(i) == s2.charAt(i); i++) prefix += s1.charAt(i);
- 01-27-2012, 08:06 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,408
- Blog Entries
- 7
- Rep Power
- 17
Re: Code architecture
I'd get the prefix after the loop has finished; it doesn't matter much for your small examples but if the common prefix happens to be large, a lot of Strings have been created and thrown away during those loops.
kind regards,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
- 01-27-2012, 08:21 PM #3
Senior Member
- Join Date
- Jan 2012
- Posts
- 210
- Rep Power
- 2
Re: Code architecture
Do You mean each time I concatenate String object, it is actually new String object, because of String immutability?
So, is something like this best solution?
Java Code:int i; for (i = 0; i < min && s1.charAt(i) == s2.charAt(i); i++); prefix = s1.substring(0, i);Last edited by diamonddragon; 01-27-2012 at 08:27 PM.
- 01-27-2012, 08:29 PM #4
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,408
- Blog Entries
- 7
- Rep Power
- 17
Similar Threads
-
What is MVC architecture, how do I use it
By africanhacker in forum New To JavaReplies: 6Last Post: 03-21-2011, 02:49 PM -
Architecture of pos
By j-mi-jim in forum Advanced JavaReplies: 6Last Post: 11-12-2010, 01:57 PM -
Question about architecture
By sdmente in forum Advanced JavaReplies: 7Last Post: 07-28-2010, 01:07 PM -
Architecture Rules 2.0.1
By JavaBean in forum Java SoftwareReplies: 0Last Post: 11-17-2007, 02:03 PM -
Architecture of Any IDE...
By vikki_pu in forum Other IDEsReplies: 5Last Post: 10-30-2007, 01:08 PM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks