• Latest
  • Trending
How to work with String.Create in C#

How to work with String.Create in C#

May 28, 2022
Improving hydrogen peroxide production through sustainable photocatalysis

Improving hydrogen peroxide production through sustainable photocatalysis

June 28, 2022
Kinverch 750W Continuous/1500W Peak Power Inverter DC 12V to 110V Car Converter AC with 2 AC Outlets and 2A USB Charging Port

Kinverch 750W Continuous/1500W Peak Power Inverter DC 12V to 110V Car Converter AC with 2 AC Outlets and 2A USB Charging Port

June 28, 2022
All heads should have SENCo qualification

All heads should have SENCo qualification

June 28, 2022
FDA Panel to Weigh Improved Booster Shots From Moderna, Pfizer

FDA Panel to Weigh Improved Booster Shots From Moderna, Pfizer

June 28, 2022
Nigeria, Japan sign .78m exchange notes on high speed boats

Nigeria, Japan sign $2.78m exchange notes on high speed boats

June 28, 2022
Democratic exasperation builds at Biden’s slow roll on Roe

Democratic exasperation builds at Biden’s slow roll on Roe

June 28, 2022
RansomHouse extortion group claims AMD as its latest victim – TechCrunch

RansomHouse extortion group claims AMD as its latest victim – TechCrunch

June 28, 2022
England captain Eoin Morgan announces retirement from international cricket

England captain Eoin Morgan announces retirement from international cricket

June 28, 2022
Q&A: Two coding-bootcamp graduates tell their stories

Q&A: Two coding-bootcamp graduates tell their stories

June 28, 2022
Chris Pratt Reacts to Internet Hatred, Religion Criticism and Backlash for ‘Healthy Daughter’ Comment

Chris Pratt Reacts to Internet Hatred, Religion Criticism and Backlash for ‘Healthy Daughter’ Comment

June 28, 2022
What is forest bathing? | Live Science

What is forest bathing? | Live Science

June 28, 2022
Priority Kid’s Digital Camera (Yellow), Kid’s 24MP Action Camera for Pictures and Video, 2 inch Display, 4X Zoom, Accessories and 32GB Memory Included

Priority Kid’s Digital Camera (Yellow), Kid’s 24MP Action Camera for Pictures and Video, 2 inch Display, 4X Zoom, Accessories and 32GB Memory Included

June 28, 2022
Dagoldinfo
Tuesday, June 28, 2022
Contact Us
Advertise
  • Home
  • World News
    Democratic exasperation builds at Biden’s slow roll on Roe

    Democratic exasperation builds at Biden’s slow roll on Roe

    G-7 nations must reject China’s Taiwan Strait claim

    G-7 nations must reject China’s Taiwan Strait claim

    Russia-Ukraine war: 21 people missing after shopping centre attack; G7 leaders agree to explore Russian oil price cap – live | World news

    Russia-Ukraine war: 21 people missing after shopping centre attack; G7 leaders agree to explore Russian oil price cap – live | World news

    How to Get Men to Share the Mental Load

    How to Get Men to Share the Mental Load

    The Surprising Success of the Truce in Yemen

    The Surprising Success of the Truce in Yemen

    Israel’s snap election grants Iran another six months to further its nuclear goal

    Israel’s snap election grants Iran another six months to further its nuclear goal

    Japan: Tokyo swelters amid worst June heatwave since 1875 | Weather News

    Japan: Tokyo swelters amid worst June heatwave since 1875 | Weather News

    Tour de France: Geraint Thomas among four Britons in Ineos squad along with Tom Pidcock, Adam Yates and Luke Rowe

    Tour de France: Geraint Thomas among four Britons in Ineos squad along with Tom Pidcock, Adam Yates and Luke Rowe

    China zero-Covid policy: Censors scrub internet after senior official’s speech on timeline for Beijing

  • Nigerian news
    Nigeria, Japan sign .78m exchange notes on high speed boats

    Nigeria, Japan sign $2.78m exchange notes on high speed boats

    APP Party To Drag APC Presidential Candidate, Tinubu To Court Over Alleged False Academic Qualifications

    APP Party To Drag APC Presidential Candidate, Tinubu To Court Over Alleged False Academic Qualifications

    Senate orders fresh probe of ex-CJN over corruption allegations

    Senate orders fresh probe of ex-CJN over corruption allegations

    French minister apologises for Champions League chaos

    French minister apologises for Champions League chaos

    Oyo Speaker, Ogundoyin Appeals for Calm as Assembly Staff Demand Implementation of CONLESS

    Oyo Speaker, Ogundoyin Appeals for Calm as Assembly Staff Demand Implementation of CONLESS

    Shaibu visits community of murdered catholic priest, condemns killing – Nigerian Observer

    Shaibu visits community of murdered catholic priest, condemns killing – Nigerian Observer

    Atiku commends Tanko, wishes Ariowoola successful tenure

    Atiku commends Tanko, wishes Ariowoola successful tenure

    Aregbesola urges NCoS to track, recapture escaped inmates

    Aregbesola urges NCoS to track, recapture escaped inmates

    Lawyer Who Attempted To ‘Steal’ Ex-Petroleum Minister, Ajumogobia’s Client, Saying Olanipekun Is Close To Judges, Blames It On Ignorance

    Lawyer Who Attempted To ‘Steal’ Ex-Petroleum Minister, Ajumogobia’s Client, Saying Olanipekun Is Close To Judges, Blames It On Ignorance

  • Business
    Democratic exasperation builds at Biden’s slow roll on Roe

    Democratic exasperation builds at Biden’s slow roll on Roe

    G-7 nations must reject China’s Taiwan Strait claim

    G-7 nations must reject China’s Taiwan Strait claim

    Russia-Ukraine war: 21 people missing after shopping centre attack; G7 leaders agree to explore Russian oil price cap – live | World news

    Russia-Ukraine war: 21 people missing after shopping centre attack; G7 leaders agree to explore Russian oil price cap – live | World news

    How to Get Men to Share the Mental Load

    How to Get Men to Share the Mental Load

    The Surprising Success of the Truce in Yemen

    The Surprising Success of the Truce in Yemen

    Israel’s snap election grants Iran another six months to further its nuclear goal

    Israel’s snap election grants Iran another six months to further its nuclear goal

    Japan: Tokyo swelters amid worst June heatwave since 1875 | Weather News

    Japan: Tokyo swelters amid worst June heatwave since 1875 | Weather News

    Tour de France: Geraint Thomas among four Britons in Ineos squad along with Tom Pidcock, Adam Yates and Luke Rowe

    Tour de France: Geraint Thomas among four Britons in Ineos squad along with Tom Pidcock, Adam Yates and Luke Rowe

    China zero-Covid policy: Censors scrub internet after senior official’s speech on timeline for Beijing

  • Entertainment
    Chris Pratt Reacts to Internet Hatred, Religion Criticism and Backlash for ‘Healthy Daughter’ Comment

    Chris Pratt Reacts to Internet Hatred, Religion Criticism and Backlash for ‘Healthy Daughter’ Comment

    TBS Has No Comment on Samantha Bee’s Incendiary Rant (Again)

    TBS Has No Comment on Samantha Bee’s Incendiary Rant (Again)

    The Gang Will get Immortalized: The 1001 Greatest Jokes From Each Episode of ‘It’s All the time Sunny’ (Half 1)

    The Gang Will get Immortalized: The 1001 Greatest Jokes From Each Episode of ‘It’s All the time Sunny’ (Half 1)

    Dakota Johnson Is Set to Play ‘Madame Web’ With Emma Roberts On Board

    Dakota Johnson Is Set to Play ‘Madame Web’ With Emma Roberts On Board

    Vang Brothers’ Supernatural Thriller ‘They Live in the Grey’ Trailer

    Vang Brothers’ Supernatural Thriller ‘They Live in the Grey’ Trailer

    We Hit the Road with Our Home Video Pick of the Week

    We Hit the Road with Our Home Video Pick of the Week

    Christian Bale on the monstrous origins of Gorr the God Butcher

    Christian Bale on the monstrous origins of Gorr the God Butcher

    James Corden’s ‘The Late Late Show’ Tapes in London With Billie Eilish

    James Corden’s ‘The Late Late Show’ Tapes in London With Billie Eilish

    Stella McCartney angry at Victoria Beckham

    Stella McCartney angry at Victoria Beckham

  • Science
    Improving hydrogen peroxide production through sustainable photocatalysis

    Improving hydrogen peroxide production through sustainable photocatalysis

    What is forest bathing? | Live Science

    What is forest bathing? | Live Science

    Covid-19: What are the risks of catching the virus multiple times?

    Covid-19: What are the risks of catching the virus multiple times?

    SpaceX’s Starship Super Heavy rocket at launch pad for tests

    SpaceX’s Starship Super Heavy rocket at launch pad for tests

    Intentional Travel for the Curious

    Intentional Travel for the Curious

    African wild dogs give birth 22 days later than they did 30 years ago due to climate change

    African wild dogs give birth 22 days later than they did 30 years ago due to climate change

    Warmer winters could wipe out Antarctica’s only native insect | Science

    Warmer winters could wipe out Antarctica’s only native insect | Science

    EXPERT REACTION/BRIEFING: How much of our extreme weather is down to manmade climate change?

    EXPERT REACTION/BRIEFING: How much of our extreme weather is down to manmade climate change?

    Understanding Earthquakes Triggered by Wastewater Injection

    Understanding Earthquakes Triggered by Wastewater Injection

  • Technology
    Q&A: Two coding-bootcamp graduates tell their stories

    Q&A: Two coding-bootcamp graduates tell their stories

    Crypto exchange Huobi may axe 30% of staff

    Crypto exchange Huobi may axe 30% of staff

    As Muddy As You Want

    As Muddy As You Want

    Apple may have a major change in store for the M2 chip

    Apple may have a major change in store for the M2 chip

    Expedia hires chief security officer; Microsoft technical fellow departing; and more – GeekWire

    Expedia hires chief security officer; Microsoft technical fellow departing; and more – GeekWire

    As HPC Chip Sizes Grow, So Does the Need For 1kW+ Chip Cooling

    As HPC Chip Sizes Grow, So Does the Need For 1kW+ Chip Cooling

    iPhone 14 to launch around September, component shipments reportedly underway

    iPhone 14 to launch around September, component shipments reportedly underway

    Security survives the budget axe

    Security survives the budget axe

    New Acer Aspire 7 launched in India: Check price and specs

    New Acer Aspire 7 launched in India: Check price and specs

  • Lifestyle
    FDA Panel to Weigh Improved Booster Shots From Moderna, Pfizer

    FDA Panel to Weigh Improved Booster Shots From Moderna, Pfizer

    Putting Phone In Silent Mode May Actually Increase Stress: Study

    Putting Phone In Silent Mode May Actually Increase Stress: Study

    US Supreme Court Sides With Doctors Challenging Opioid Convictions

    US Supreme Court Sides With Doctors Challenging Opioid Convictions

    21 Best Belts For Men Of 2022 (Casual & Dress Styles)

    21 Best Belts For Men Of 2022 (Casual & Dress Styles)

    3 Effective Business Strategies for Success

    3 Effective Business Strategies for Success

    5 Outdoor Designer Furniture Brands to Make Your Summer Stylish

    5 Outdoor Designer Furniture Brands to Make Your Summer Stylish

    Does Menopause Affect Your Memory?

    Does Menopause Affect Your Memory?

    The 18 Best Cobbler Recipes For Every Sweet Summer Party

    The 18 Best Cobbler Recipes For Every Sweet Summer Party

    We have grasshoppers when we need ants

    We have grasshoppers when we need ants

  • Education
    All heads should have SENCo qualification

    All heads should have SENCo qualification

    First, Know Thyself. Then, Pick a Career Path

    First, Know Thyself. Then, Pick a Career Path

    m Canadian scholarship for developing nations

    $80m Canadian scholarship for developing nations

    PSEB Class 12 result 2022: Ludhiana girl is the topper, 96.96% students pass

    PSEB Class 12 result 2022: Ludhiana girl is the topper, 96.96% students pass

    We must help our youngest navigate risks from climate change

    We must help our youngest navigate risks from climate change

    Excelsior Scholarship’s fine print limits recipient numbers, report finds

    Excelsior Scholarship’s fine print limits recipient numbers, report finds

    The Hero Awards Program honors standout educators

    The Hero Awards Program honors standout educators

    When College Students in Crisis Ask for Help, Will They Be Kicked Off Campus? Depends on the College.

    When College Students in Crisis Ask for Help, Will They Be Kicked Off Campus? Depends on the College.

    Democracy and Education | Higher Ed Gamma

    Democracy and Education | Higher Ed Gamma

  • Sport
    England captain Eoin Morgan announces retirement from international cricket

    England captain Eoin Morgan announces retirement from international cricket

    England vs India live stream: Edgbaston ready to host rearranged fifth and final Test

    England vs India live stream: Edgbaston ready to host rearranged fifth and final Test

    UFC 276: Max Holloway relishes history and legacy trilogy vs Alexander Volkanovski in Las Vegas

    UFC 276: Max Holloway relishes history and legacy trilogy vs Alexander Volkanovski in Las Vegas

    Wimbledon 2022 latest: Serena Williams and Rafael Nadal to play first round matches

    Wimbledon 2022 latest: Serena Williams and Rafael Nadal to play first round matches

    Raheem Sterling future: Man City open to letting player join Chelsea

    Raheem Sterling future: Man City open to letting player join Chelsea

    Sai Praneeth, Sameer Verma lose in Malaysia Open | Badminton News

    Sai Praneeth, Sameer Verma lose in Malaysia Open | Badminton News

    MLB: 12 suspended after mass brawl between Mariners and Angels

    MLB: 12 suspended after mass brawl between Mariners and Angels

    Big 12 targeting Brett Yormark to replace Bob Bowlsby as commissioner, sources say

    Big 12 targeting Brett Yormark to replace Bob Bowlsby as commissioner, sources say

    Angel City FC, Mexico women to play Sept. 5 friendly in LA

    Angel City FC, Mexico women to play Sept. 5 friendly in LA

  • Product
    Kinverch 750W Continuous/1500W Peak Power Inverter DC 12V to 110V Car Converter AC with 2 AC Outlets and 2A USB Charging Port

    Kinverch 750W Continuous/1500W Peak Power Inverter DC 12V to 110V Car Converter AC with 2 AC Outlets and 2A USB Charging Port

    Priority Kid’s Digital Camera (Yellow), Kid’s 24MP Action Camera for Pictures and Video, 2 inch Display, 4X Zoom, Accessories and 32GB Memory Included

    Priority Kid’s Digital Camera (Yellow), Kid’s 24MP Action Camera for Pictures and Video, 2 inch Display, 4X Zoom, Accessories and 32GB Memory Included

    Night Owl Security SPF-CAMP-2A Camera Adapter with 4-Way Power Splitter, Black

    Night Owl Security SPF-CAMP-2A Camera Adapter with 4-Way Power Splitter, Black

    La Roche-Posay Toleriane Double Repair Face Moisturizer, Daily Moisturizer Face Cream with Ceramide and Niacinamide for All Skin Types, Oil Free, Fragrance Free

    La Roche-Posay Toleriane Double Repair Face Moisturizer, Daily Moisturizer Face Cream with Ceramide and Niacinamide for All Skin Types, Oil Free, Fragrance Free

    3D Makeup Practice Face, The Perfect Aid to Practicing Makeup, Silicone Face Eye Makeup Practice Board for Professional Makeup Artists Students and Beginners to practice eyesmakeup with 5 Piece Cosmet

    3D Makeup Practice Face, The Perfect Aid to Practicing Makeup, Silicone Face Eye Makeup Practice Board for Professional Makeup Artists Students and Beginners to practice eyesmakeup with 5 Piece Cosmet

    LED Tail Light Replacement for Jeep 2018+ Wrangler JL [Black-Lens] [Plug-n-Play] [IP67 Waterproof] LED Brake Light Compatible with Jeep Wrangler JL Accessories

    LED Tail Light Replacement for Jeep 2018+ Wrangler JL [Black-Lens] [Plug-n-Play] [IP67 Waterproof] LED Brake Light Compatible with Jeep Wrangler JL Accessories

    WORKPRO Large Pliers & Wrench Set 6-Piece (10″ Water Pump Pliers, 10″ Slip Joint Pliers, 8″ Long Nose Pliers, 8″ Linesman Pliers, 6″ Diagonal Pliers, 8″ Adjustable Wrench) for DIY & Home Use, W001329A

    WORKPRO Large Pliers & Wrench Set 6-Piece (10″ Water Pump Pliers, 10″ Slip Joint Pliers, 8″ Long Nose Pliers, 8″ Linesman Pliers, 6″ Diagonal Pliers, 8″ Adjustable Wrench) for DIY & Home Use, W001329A

    It’s a 10 Haircare Miracle Leave-In Plus Keratin Spray, 10 fl. oz (Pack of 3)

    It’s a 10 Haircare Miracle Leave-In Plus Keratin Spray, 10 fl. oz (Pack of 3)

    ONXE LED USB Clock Fan with Real Time Display Function,USB Clock Fans,Silver,1 Year Warranty (Clock)

    ONXE LED USB Clock Fan with Real Time Display Function,USB Clock Fans,Silver,1 Year Warranty (Clock)

No Result
View All Result
Dagoldinfo
No Result
View All Result

How to work with String.Create in C#

by dagoldtech
May 28, 2022
in Technology
0 0
0


String handling is one of the most performance-critical areas in any application. Because strings are immutable, you can very easily accumulate many string objects very quickly, resulting in memory resource allocations that will impact application performance adversely.

When you add strings or extract substrings from a string, new string instances are created. Same goes when you perform operations such as string concatenation, which creates new string objects rather than reusing existing ones. We’ve seen how we can take advantage of the StringBuilder class when concatenating strings to reduce the number of string instances created and also reduce the allocations.

Continuing our discussion on working with strings efficiently, in this article we’ll look at how we can use the String.Create method to create strings with no resource overhead whatsoever. While string compression is a great technique for reducing resource consumption generally, String.Create is another technique you can use to handle strings efficiently—but only in certain circumstances, which we’ll discuss.

To work with the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create a console application project in Visual Studio 2022

First off, let’s create a .NET Core console application project in Visual Studio. Assuming Visual Studio 2022 is installed in your system, follow the steps outlined below to create a new .NET Core console application project.

  1. Launch the Visual Studio IDE.
  2. Click on “Create a new project.”
  3. In the “Create a new project” window, select “Console App” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window shown next, specify the name and location for the new project.
  6. In the “Additional Information” window, select .NET 6.0 as the runtime and click Next
  7. Click Create.

We’ll use this .NET 6 console application project to work with strings in the sections below.

Span<T> and Memory<T>

Span<T> and Memory<T> are structs that have been added in the newer versions of .NET and that help to minimize allocations. They work as a facade over a string, array, or any contiguous block of memory. They also have read-only counterparts. The read-only counterpart of the Span<T> struct is ReadOnlySpan<T>, and the read-only counterpart of Memory<T> is ReadOnlyMemory<T>.

The String.Create method in C#

The String.Create method was added in the recent versions of C#. Here is how the Create method of the String class is declared:

public static string Create<TState> (int length, TState state, System.Buffers.SpanAction<char,TState> action);

The String.Create method requires the following:

  1. The length of the string to create
  2. The data (i.e., the state)
  3. A lambda function that can transform the state into a string

The String.Create method allocates a chunk of memory on the heap to store a sequence of characters. The first parameter of this method is the length of the final string. The second parameter is the state required to build the string object. The third and last parameter is a delegate that should work on the data in the allocated heap and generate the final string object.

When you call the String.Create method, it creates a new string that has a pre-defined size determined by the value of your length argument. Note that this is the only heap allocation that will occur when you’re using the String.Create method. Since the Create method is a member of the String class, it can access the Span<char> instance that represents the internal character data of the new string instance.

The Span<char> itself is a pointer that resides on the stack but is capable of working on the heap memory. The action lambda performs the heavy lifting of populating the string that is eventually returned to you. In other words, once the execution of the lambda function is complete, the String.Create method returns a reference to the new string instance it has created.

When to use the String.Create method

String.Create has a few specific use cases. First, you should use String.Create only in performance-critical paths. Second, you should use String.Create only when you want to build a string object when the size and format of the string are known to you. As an example, let’s say you want to log correlation Id to a log file with every method call for each and every request. You might take advantage of String.Create to build such string instances efficiently. You might also use String.Create for performance-sensitive concatenations and formatting complex strings.

Using the String.Create method

Here is a simple example of using the String.Create method:

char[] buffer = { 'a', 'e', 'i', 'o', 'u' }; 
string result = string.Create(buffer.Length, buffer, (c, b) => {
    for (int i = 0; i < c.Length; i++) c[i] = b[i];
});

Below is another example that illustrates how you can use String.Create to generate correlation Ids. Enter the following code in the Program.cs file of the console application project we created earlier.

private static readonly char[] charactersToEncode = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();
private static string GetCorrelationId(long id)
    {
        return string.Create(10, id, (buffer, value) =>
        {
            char[] characters = charactersToEncode;
            buffer[9] = characters[(value >> 5) & 31];
            buffer[8] = characters[(value >> 10) & 31];
            buffer[7] = characters[(value >> 15) & 31];
            buffer[6] = characters[(value >> 20) & 31];
            buffer[5] = characters[(value >> 25) & 31];
            buffer[4] = characters[(value >> 30) & 31];
            buffer[3] = characters[(value >> 35) & 31];
            buffer[2] = characters[(value >> 40) & 31];
            buffer[1] = characters[(value >> 45) & 31];
            buffer[0] = characters[(value >> 50) & 31];
        });
    }

To get a new correlation Id, you can call the GetCorrelationId method from the Main method as shown below:

static async Task Main(string[] args)
    {
        Console.WriteLine(GetCorrelationId(DateTime.UtcNow.Ticks));
        Console.ReadKey();
    }

String.Create limitations and best practices

When using String.Create, you should first of all keep its limitations in mind. You should know the size of the string you want to create in advance, which will require knowing the length of the state objects that the final string will be composed of.

There are also two best practices you should adhere to when working with the String.Create method. First, it’s wise to benchmark the performance of your application to ensure that using String.Create actually yields better results. Second, if you’re using multiple objects for the state, be sure to take advantage of ValueTuples.

Finally, note that String.Create might not be a good choice in certain scenarios. You should not use String.Create when readability or culture is important for your application or your development team.

So, whether you should use String.Create or not depends on the trade-offs between its downsides and performance benefits. My advice is, benchmark your code, see the results, and then decide. I’ll write more on writing high performance code in future posts here.

Copyright © 2022 IDG Communications, Inc.



Source link

YOU MAY ALSO LIKE

Q&A: Two coding-bootcamp graduates tell their stories

Crypto exchange Huobi may axe 30% of staff

ShareTweetShareSendShareShare

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Home
  • World News
  • Nigerian news
  • Business
  • Entertainment
  • Science
  • Technology
  • Lifestyle
  • Education
  • Sport
  • Product
Call us for advertisement: + 234 8111770774 Email: advertise@dagoldinfo.com.ng

© 2022 DagoldInfo

No Result
View All Result
  • Home
  • World News
  • Nigerian news
  • Business
  • Entertainment
  • Science
  • Technology
  • Lifestyle
  • Education
  • Sport
  • Product

© 2022 DagoldInfo

Welcome Back!

Login to your account below

Forgotten Password?

Retrieve your password

Please enter your username or email address to reset your password.

Log In