Use unmanaged code to directly modify strings

Source: Internet
Author: User

In the string method, string operation methods such as ToUpper generate a new string, which increases the running expense. An alternative is to operate strings directly using unmanaged code. For example, replace ToUpper:
Using System;

Public class Test
{
Public static void Main (string [] args)
{
String str = "hello ";
ToUpper (str );
Console. WriteLine (str );
}
Private static unsafe void ToUpper (string str)
{
Fixed (char * pfixed = str)
For (char * p = pfixed; * p! = 0; p ++)
{
* P = char. ToUpper (* p );
}
}
}

Fixed statement:
Format: fixed (type * ptr = expr) statement
It aims to prevent variables from being located by the garbage collector.
Where:
Type is not managed type or void
Ptr is the pointer name.
Expr is an expression that can be implicitly converted to type *.
Statement is an executable statement or block.
The fixed statement can only be used in the context of unsafe. The fixed statement sets a pointer to the managed variable and "locks" the variable during statement execution. If there is no fixed statement, the pointer to the managed variable will have little effect, because garbage collection may be unpredictable to relocate the variable.
After statement is executed, all locked variables are unlocked and restricted by garbage collection. Therefore, do not point to variables other than fixed statements. In unsafe mode, memory can be allocated on the stack. The stack is not restricted by garbage collection, so it does not need to be locked.

However, during compilation, the use of unmanaged code requires/unsafe to pass.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.