logo
down
shadow

Alternative/faster method to slow StreamWriter to print strings to a file in C#


Alternative/faster method to slow StreamWriter to print strings to a file in C#

By : Umit TAS
Date : November 18 2020, 03:49 PM
I wish this helpful for you I profiled this and it looks like it is completely the opposite. I was able to get about .25GB/s written to a standard 10K rpm drive (no SSD). It looks like you're calling this function a lot and writing to the file by connecting to it new each time. Try something like this (I snipped this together quickly from a piece of old console logging code, so it might be a bit buggy, and error handling is certainly not complete):
code :
public static class LogWriter
{
    // we keep a static reference to the StreamWriter so the stream stays open
    // this could be closed when not needed, but each open() takes resources
    private static StreamWriter writer = null;
    private static string LogFilePath = null;

    public static void Init(string FilePath)
    {
        LogFilePath = FilePath;
    }

    public static void WriteLine(string LogText)
    {
        // create a writer if one does not exist
        if(writer==null)
        {
            writer = new StreamWriter(File.Open(LogFilePath,FileMode.OpenOrCreate,FileAccess.Write,FileShare.ReadWrite));
        }
        try
        {
            // do the actual work
            writer.WriteLine(LogText);
        }
        catch (Exception ex)
        {
            // very simplified exception logic... Might want to expand this
            if(writer!=null)
            {
                writer.Dispose();
            }
        }
    }

    // Make sure you call this before you end
    public static void Close()
    {
        if(writer!=null)
        {
            writer.Dispose();
            writer = null;
        }
    }
}


Share : facebook icon twitter icon
file_exists() is too slow in PHP. Can anyone suggest a faster alternative?

file_exists() is too slow in PHP. Can anyone suggest a faster alternative?


By : طنطا سيتي
Date : March 29 2020, 07:55 AM
To fix the issue you can do file_exists() should be a very inexpensive operation. Note too that file_exists builds its own cache to help with performance.
See: http://php.net/manual/en/function.file-exists.php
Writing to file using StreamWriter much slower than file copy over slow network

Writing to file using StreamWriter much slower than file copy over slow network


By : Alexander S.
Date : March 29 2020, 07:55 AM
hop of those help? If you create your StreamWriter using default buffer sizes then the underlying SMB protocol will be issuing write requests in chunks no larger than 4096 bytes, which means a large number of round-trips over the network. You could increase your StreamWriter's buffer size up to a maximum of 64k in order to reduce the number of round trips:
code :
using (var outfile = new StreamWriter(myRemoteFilePath, false, Encoding.ASCII, 0x10000))
Is there a faster alternative to counting special characters for 100,000 short strings in R?

Is there a faster alternative to counting special characters for 100,000 short strings in R?


By : user2619236
Date : March 29 2020, 07:55 AM
I wish this helpful for you The base R functions are much faster. Here is a sum/grepl solution and 4 different ways of calling the two functions.
code :
library(microbenchmark)
library(ggplot2)
library(dplyr)
library(stringr)
library(purrr)

# custom function that accepts string input and counts the number 
# of non-alphanum characters
count_non_alnum <- function(x) {
  stringr::str_detect(x, "[^[:alnum:] ]") %>% sum()
}

count_non_alnum2 <- function(x) {
  sum(grepl("[^[:alnum:] ]", x))
}

# character vector of length 100K
vec <- rep("Hello. World.", 100)  

# tokenize individual characters for each string
vec_tokens <- purrr::map(vec, function(x) {
  stringr::str_split(x, "") %>% unlist()
})


# count non-alphanum characters
mb <- microbenchmark(
  Danny_purrr = purrr::map(vec_tokens, count_non_alnum),
  Rui_purrr = purrr::map(vec_tokens, count_non_alnum2),
  Danny_base = sapply(vec_tokens, count_non_alnum),
  Rui_base = sapply(vec_tokens, count_non_alnum2),
  unit = "relative"
)
mb
#Unit: relative
#        expr       min        lq      mean    median        uq       max neval cld
# Danny_purrr 58.508234 56.440147 52.854162 53.890724 53.464640 25.855456   100   c
#   Rui_purrr  1.026362  1.021998  1.011265  1.025648  1.025087  1.558001   100 a  
#  Danny_base 58.643098 56.398330 52.491478 53.857666 52.821759 27.981780   100  b 
#    Rui_base  1.000000  1.000000  1.000000  1.000000  1.000000  1.000000   100 a  


autoplot(mb)
String.format slow, need faster alternative

String.format slow, need faster alternative


By : TC Sefa Bozkurt Kerk
Date : March 29 2020, 07:55 AM
To fix this issue I find it hard to believe that simple string.Format calls are causing your slowness problems - it's generally a very fast call, especially for nice simple ones like most of yours.
But one thing that might give you a few microseconds...
cannot write strings to file using '.writeline' method of a streamwriter

cannot write strings to file using '.writeline' method of a streamwriter


By : Chudipal Chudos
Date : March 29 2020, 07:55 AM
Does that help I want to write a simple string in a text file using the stream writer class,But it doesn't seem to work(and there are no errors).here's my code:
Related Posts Related Posts :
  • How to use Addfields in MongoDB C# Aggregation Pipeline
  • MsTest TestCleanup method not called when an unhandled exception is thrown
  • missing last data when exporting gridview to excel
  • How to add array of objects to List in c#
  • Lambda Expression to order (sort) my list collection
  • Library for displaying music notation
  • How to compare two dictionaries in c# and get the output as True and False after validation
  • specify fields to be serialized with JSON
  • How do you obtain the content of a specific node using XmlDocument in C#?
  • How to ignore the first line in a csv file when you read the csv file in C#
  • c# - Problem calling public void from class
  • How to tell a class which objects it should create? Type vs. object confusion :(
  • Save CheckBox state to xml
  • WIX CAQuietExec NETSH Command Fails
  • Issues sending http put request every 60 seconds to RoR app
  • ConfigurationManager.ConnectionStrings.ConnectionString Issue
  • Real size WPF controls for printing
  • How to cancel properly?
  • C# String multiplication error
  • Using Solrnet and Assigning Attributes with Entity Framework Generated POCOs
  • Regex pattern for single backslash
  • TextBox: insert spaces for credit card number?
  • C# DLL loaded for exe-application is not found when launching similar DLL by rundll32.exe
  • Debug a Windows Service with WCF library
  • Open a file from an external assembly?
  • Servicestack RegistrationFeature Unable to bind request
  • Index was outside the bounds of the array confusion
  • Error in Xml to List code. The ':' character, hexadecimal value 0x3A, cannot be included in a name
  • I am trying to do a while loop with a string conditional statement in C#
  • C# 'Cannot access a disposed object. Object name: 'SslStream'.'
  • How to make Gecko use seperate CookieContainer per instance?
  • C# Advanced form "please wait"
  • Send and Receive data C# using network stream
  • How to discover that appsettings changed in C#?
  • Check what needs full trust
  • What is the execution order of an MVC Razor view/layout
  • Table designer (Entity Framework) is too resource intense
  • How to clean up an exception string so it can be displayed via Javascript Alert?
  • Configuring Amazon SES Feedback Notifications via Amazon SNS in ASP.NET MVC (C#)
  • C# api responce and request
  • Dynamodb putitem function not working properly
  • theme in windows phone(light or dark) using c#
  • Backup attached database file(.mdf) using c# and SQL Server
  • What is 'TextFile' and where it is uses in WPF project
  • Using same alias for multiple namespaces
  • how to move mails into separate folders
  • Multithreaded Uploader
  • Memory fragmentation?
  • C# correct exception handling
  • "Could not open macro storage" when accessing using file on another machine
  • How to access other directories of hosted server
  • C# Jagged Array check if value exists/true
  • Why can't I type Clone() properly?
  • exception on accessing dictionary from list
  • Getting the immediate response from server without waiting to 200 message
  • Why am I getting exception Directory Is Not empty?
  • Could not load file or assembly 'CefSharp.dll' or one of its dependencies
  • Sending Email By Using C# in unity3D?
  • Correct usage of await async in webapi
  • Program update code issue
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org