Some times I need a sub string of a string and I noticed that if you add final keyword, Java compiler makes a small optimization, isn't it?
For example :
String name = "this is a simple string";
String simple = name.substring(0,4);
Here Java creates two strings
but if you write this code in different way you get rid of one extra allocation
final String name = "this is a simple string";
final String simple = name.substring(0,4);
Both objects points to the same memory block and String object itself has a constant context
Am I right?
I am not sure about this conclusions, so, I will check it again when I have time.
If you know something how to use final for Strings and what exactly java compiler does,
I'll be pleased if someone share his knowledges in this area
Tuesday, November 30, 2010
Bugs aligned to CString
Today I noticed a funny thing. Class CString C++ sometimes works like class String in Java
For example :
Conclusion : don't mix API because you never know about class implementation.
Fix is simple, just use mText.Empty() or mText[n] to modify string and never (LPTSTR)(mText)[n]
For example :
class Example
{
CString mName;
public:
void setName(const CString & name)
{
mName = name;
}
void modify()
{
memset((VPVOID)(LPTSTR) mName,65,mName.GetLength()*sizeof(TCHAR));
}
}
class Other
{
// we set up this name somewere in code
public:
CString getName() const
{
return mName;
}
}
void main()
{
std::autoptr o1 =
std::autoptr(
new Other(_T("simple string")));
Example ex1;
ex.setName( o1->getName() );
ex.modyfy();
// here you will have empty string for o1 and for ex classes
// because it refers to the same string data in memory
// so both
classes will contain modified data
}
Conclusion : don't mix API because you never know about class implementation.
Fix is simple, just use mText.Empty() or mText[n] to modify string and never (LPTSTR)(mText)[n]
Subscribe to:
Posts (Atom)