-
What is wrong with these codes
Hi
Need help in these
1.How can I Optimize this Java code. Assume all variables have been declared and have the correct data type.
String str = "";
for( int i=0; i < 1000; i++ ) {
str += myStringArray[i];
}
2.
What's wrong with this Java code? Assume all variables have been declared and have the correct data type.
try {
PreparedStatement stmt = conn.prepareStatement( "select top ? my_column from my_table" );
stmt.setInt( 1, myNum );
rs = stmt.executeQuery();
} finally {
conn.close();
}
3.
What is the output of this Java fragment?
int a = 0;
int b = 0;
if( false & a++ > 0 ) {
a = 100;
}
if( false && ++b > 0 ) {
b = 100;
}
Please reply
Regards
System.out.println(a);
System.out.println(b);
-
1:
Code:
StringBuffer sb=new StringBuffer();
for( int i=0; i < 1000; i++ ) {
sb.append(myStringArray[i]);
}
2:
don't know, havn't got my online sql doc going for the moment
3:
1
0
eschew obfuscation
-
go Tiger, sjalle ;-)
1. ...or, as of java 1.5,
Code:
StringBuilder sb=new StringBuilder();
for( int i=0; i < 1000; i++ ) {
sb.append(myStringArray[i]);
}
should be even faster.
Explanation:
Strings are immutable. Thus, when using str += myStringArray[i], one thousand objects and one need to be created, each being a prefix of all subsequent ones and all but the last object are prone to garbage collection immediately after use. All this object creation and discarding is relatively expensive.
StringBuffers, in contrast, are mutable. So only one StringBuffer object is created and then stepwise extended, which is what you really intended in the first place, I guess.
StringBuilders are just an unsynchronized version of StringBuffers, ie. they do not take care if any other thread is using (possibly modifying) them. As is most often the case, such objects (ie. here: objects used to build up a sequence of characters, but keeping this pattern in mind is never a waste), are known only to one thread anyway such that synchronization is not needed. The performance gain may not be dramatic, but it IS there.
Last edited by meisl; 03-04-2005 at 08:30 PM.
-
I installed 1.5 a week ago (and my JBuilder 8 took it in its stride, documentation,
codeinsight and all). Very nice.
But when that is said; any class doing 'endless' string concatenation must, at
certain intervals, reallocate (or at least allocate and link up) more memory, the good
thing with the buffer/builder classes is that they do it in bigger chunks, i.e. less frequent.
eschew obfuscation
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks