Skip to content

Inefficient string function implementation #1714

@vasily-kirichenko

Description

@vasily-kirichenko

This line of code

let s = string 22

compiles to this:

object obj = 22;
if (obj != null)
{
	IFormattable formattable = obj as IFormattable;
	if (formattable != null)
	{
		IFormattable formattable2 = formattable;
		formattable2.ToString(null, (IFormatProvider)CultureInfo.InvariantCulture);
	}
	else
	{
		object obj2 = obj;
		obj2.ToString();
	}
}
  1. Why check for null after boxing?
  2. Why we need to ask for IFormatProvider for ints?
  3. Why we need to format it with InvariantCulture?
  4. Why intermediate obj2 variable?

As I understand the function is defined here https://github.com/Microsoft/visualfsharp/blob/master/src/fsharp/FSharp.Core/prim-types.fs#L4485

[<CompiledName("ToString")>]
let inline string (x: ^T) = 
        anyToString "" x
        // since we have static optimization conditionals for ints below, we need to special-case Enums.
        // This way we'll print their symbolic value, as opposed to their integral one (Eg., "A", rather than "1")
        when ^T struct = anyToString "" x
        when ^T : float      = (# "" x : float      #).ToString("g",CultureInfo.InvariantCulture)
        when ^T : float32    = (# "" x : float32    #).ToString("g",CultureInfo.InvariantCulture)
        when ^T : int64      = (# "" x : int64      #).ToString("g",CultureInfo.InvariantCulture)
        when ^T : int32      = (# "" x : int32      #).ToString("g",CultureInfo.InvariantCulture)
        when ^T : int16      = (# "" x : int16      #).ToString("g",CultureInfo.InvariantCulture)
        when ^T : nativeint  = (# "" x : nativeint  #).ToString()
        when ^T : sbyte      = (# "" x : sbyte      #).ToString("g",CultureInfo.InvariantCulture)
        when ^T : uint64     = (# "" x : uint64     #).ToString("g",CultureInfo.InvariantCulture)
        when ^T : uint32     = (# "" x : uint32     #).ToString("g",CultureInfo.InvariantCulture)
        when ^T : int16      = (# "" x : int16      #).ToString("g",CultureInfo.InvariantCulture)
        when ^T : unativeint = (# "" x : unativeint #).ToString()
        when ^T : byte       = (# "" x : byte       #).ToString("g",CultureInfo.InvariantCulture)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions