mconv

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 18, 2025 License: MIT Imports: 3 Imported by: 8

README

mconv

English | 中文

A lightweight Go type conversion library with high performance.

Installation

go get github.com/graingo/mconv

Features

  • Simple and intuitive API
  • Zero dependencies
  • Comprehensive type conversion support
  • Thread-safe
  • High performance with caching mechanisms
  • Generic support (Go 1.18+)
  • Reflection result caching

Basic Usage

// Basic type conversions
str := mconv.ToString(123)        // "123"
num := mconv.ToInt("123")         // 123
b := mconv.ToBool(1)              // true
f := mconv.ToFloat64("123.45")    // 123.45
t := mconv.ToTime("2006-01-02")   // time.Time

// With error handling
str, err := mconv.ToStringE(123)  // "123", nil
num, err := mconv.ToIntE("abc")   // 0, error

// Complex type conversions
slice := mconv.ToSlice([]int{1, 2, 3})  // []interface{}{1, 2, 3}
strSlice := mconv.ToStringSlice([]int{1, 2, 3}) // []string{"1", "2", "3"}
m := mconv.ToMap(map[string]int{"a": 1}) // map[string]interface{}{"a": 1}

// JSON conversions
jsonStr := mconv.ToJSON(map[string]interface{}{"name": "John"}) // {"name":"John"}
personMap := mconv.ToMapFromJSON(`{"name":"Jane"}`) // map[string]interface{}{"name": "Jane"}

Generic Support (Go 1.18+)

import "github.com/graingo/mconv/complex"

// Slice conversions with generics
strSlice := complex.ToSliceT[string]([]int{1, 2, 3}) // []string{"1", "2", "3"}
intSlice := complex.ToSliceT[int]([]string{"1", "2", "3"}) // []int{1, 2, 3}

// Map conversions with generics
strMap := complex.ToMapT[string, string](map[string]int{"a": 1}) // map[string]string{"a": "1"}
intMap := complex.ToMapT[string, int](map[string]interface{}{"a": "1"}) // map[string]int{"a": 1}

Performance Optimization

// Set cache sizes
mconv.SetStringCacheSize(2000)       // Set string cache size (default 1000)
mconv.SetTimeCacheSize(200)          // Set time cache size (default 100)
mconv.SetTypeInfoCacheSize(1000)     // Set type info cache size (default 1000)
mconv.SetConversionCacheSize(1000)   // Set conversion cache size (default 1000)

// Clear caches
mconv.ClearStringCache()             // Clear string cache
mconv.ClearTimeCache()               // Clear time cache
mconv.ClearTypeInfoCache()           // Clear type info cache
mconv.ClearConversionCache()         // Clear conversion cache
mconv.ClearAllCaches()               // Clear all caches

Benchmark Results

The following benchmark results were measured on an Apple M2 processor:

BenchmarkToString-8                 13534419               107.5 ns/op            8 B/op           1 allocs/op
BenchmarkToInt-8                    100000000               10.91 ns/op            0 B/op           0 allocs/op
BenchmarkToBool-8                   178200254                6.75 ns/op            0 B/op           0 allocs/op
BenchmarkToFloat64-8                54603055                20.84 ns/op            0 B/op           0 allocs/op
BenchmarkToTime-8                   15548144                76.57 ns/op           32 B/op           1 allocs/op
BenchmarkToSlice-8                  35479252                33.26 ns/op           40 B/op           2 allocs/op
BenchmarkToStringSlice-8             3392653               364.7 ns/op           120 B/op           8 allocs/op
BenchmarkToMap-8                     7964676               153.1 ns/op           336 B/op           2 allocs/op
BenchmarkToJSON-8                    3466358               348.2 ns/op           192 B/op           7 allocs/op

Generic functions:

BenchmarkToSliceT-8                  2906990               397.6 ns/op          136 B/op           6 allocs/op
BenchmarkToMapT-8                    1654909               723.4 ns/op          688 B/op           7 allocs/op

Reflection Caching Benefits

Reflection caching is a key feature of the mconv library that significantly improves type conversion performance. The following benchmark results demonstrate the performance advantages of reflection caching:

BenchmarkReflectionCache_TypeInfo/WithoutCache-8           8842224               133.9 ns/op            56 B/op           7 allocs/op
BenchmarkReflectionCache_TypeInfo/WithCache-8             25792029                49.03 ns/op            0 B/op           0 allocs/op

From these results, we can observe:

  1. Performance Improvement: With reflection caching, processing the same type of reflection operations is about 2.7 times faster (from 133.9 ns/op to 49.03 ns/op).
  2. Memory Optimization: With caching, memory allocation is reduced from 56 bytes and 7 allocations per operation to 0 bytes and 0 allocations, completely eliminating memory allocation overhead.
  3. Throughput Increase: The number of operations that can be processed per second increases from about 8.8 million to about 25.8 million, an improvement of approximately 192%.

For large data structures, the benefits are even more significant:

BenchmarkLargeSliceConversion/WithoutCache-8                  9327             121340 ns/op         46738 B/op        1747 allocs/op
BenchmarkLargeSliceConversion/WithCache-8                     9620             121506 ns/op         46738 B/op        1747 allocs/op

These advantages are particularly evident in applications that process large datasets or require frequent type conversions. Reflection caching stores type information and conversion results, avoiding repeated reflection operations, thereby significantly improving performance.

Use Cases

Reflection caching is particularly useful in the following scenarios:

  1. API Services: Frequently converting data between different formats
  2. Data Processing Pipelines: Processing large amounts of structurally similar data
  3. ORM and Data Mapping: Mapping between database records and structs
  4. Configuration Processing: Parsing and converting configuration data in various formats
  5. JSON/XML Processing: Frequent serialization and deserialization operations

License

MIT License

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ToString convert any type to string.
	ToString = basic.ToString
	// ToStringE convert any type to string with error.
	ToStringE = basic.ToStringE

	// ToInt convert any type to int.
	ToInt = basic.ToInt
	// ToIntE convert any type to int with error.
	ToIntE = basic.ToIntE
	// ToInt64 convert any type to int64.
	ToInt64 = basic.ToInt64
	// ToInt64E convert any type to int64 with error.
	ToInt64E = basic.ToInt64E
	// ToInt32 convert any type to int32.
	ToInt32 = basic.ToInt32
	// ToInt32E convert any type to int32 with error.
	ToInt32E = basic.ToInt32E
	// ToInt16 convert any type to int16.
	ToInt16 = basic.ToInt16
	// ToInt16E convert any type to int16 with error.
	ToInt16E = basic.ToInt16E
	// ToInt8 convert any type to int8.
	ToInt8 = basic.ToInt8
	// ToInt8E convert any type to int8 with error.
	ToInt8E = basic.ToInt8E

	// ToUint convert any type to uint.
	ToUint = basic.ToUint
	// ToUintE convert any type to uint with error.
	ToUintE = basic.ToUintE
	// ToUint64 convert any type to uint64.
	ToUint64 = basic.ToUint64
	// ToUint64E convert any type to uint64 with error.
	ToUint64E = basic.ToUint64E
	// ToUint32 convert any type to uint32.
	ToUint32 = basic.ToUint32
	// ToUint32E convert any type to uint32 with error.
	ToUint32E = basic.ToUint32E
	// ToUint16 convert any type to uint16.
	ToUint16 = basic.ToUint16
	// ToUint16E convert any type to uint16 with error.
	ToUint16E = basic.ToUint16E
	// ToUint8 convert any type to uint8.
	ToUint8 = basic.ToUint8
	// ToUint8E convert any type to uint8 with error.
	ToUint8E = basic.ToUint8E

	// ToFloat64 convert any type to float64.
	ToFloat64 = basic.ToFloat64
	// ToFloat64E convert any type to float64 with error.
	ToFloat64E = basic.ToFloat64E
	// ToFloat32 convert any type to float32.
	ToFloat32 = basic.ToFloat32
	// ToFloat32E convert any type to float32 with error.
	ToFloat32E = basic.ToFloat32E

	// ToBool convert any type to bool.
	ToBool = basic.ToBool
	// ToBoolE convert any type to bool with error.
	ToBoolE = basic.ToBoolE

	// ToComplex128 convert any type to complex128.
	ToComplex128 = basic.ToComplex128
	// ToComplex128E convert any type to complex128 with error.
	ToComplex128E = basic.ToComplex128E
	// ToComplex64 convert any type to complex64.
	ToComplex64 = basic.ToComplex64
	// ToComplex64E convert any type to complex64 with error.
	ToComplex64E = basic.ToComplex64E
	// ToTime convert any type to time.Time.
	ToTime = basic.ToTime
	// ToTimeE convert any type to time.Time with error.
	ToTimeE = basic.ToTimeE
	// ToDuration convert any type to time.Duration.
	ToDuration = basic.ToDuration
	// ToDurationE convert any type to time.Duration with error.
	ToDurationE = basic.ToDurationE
)
View Source
var (
	// ToSlice convert any type to slice.
	ToSlice = complex.ToSlice
	// ToSliceE convert any type to slice with error.
	ToSliceE = complex.ToSliceE
	// ToStringSlice convert any type to slice of string.
	ToStringSlice = complex.ToStringSlice
	// ToStringSliceE convert any type to slice of string with error.
	ToStringSliceE = complex.ToStringSliceE
	// ToIntSlice convert any type to slice of int.
	ToIntSlice = complex.ToIntSlice
	// ToIntSliceE convert any type to slice of int with error.
	ToIntSliceE = complex.ToIntSliceE
	// ToFloat64Slice convert any type to slice of float64.
	ToFloat64Slice = complex.ToFloat64Slice
	// ToFloat64SliceE convert any type to slice of float64 with error.
	ToFloat64SliceE = complex.ToFloat64SliceE

	// ToMap convert any type to map.
	ToMap = complex.ToMap
	// ToMapE convert any type to map with error.
	ToMapE = complex.ToMapE
	// ToStringMap convert any type to map of string.
	ToStringMap = complex.ToStringMap
	// ToStringMapE convert any type to map of string with error.
	ToStringMapE = complex.ToStringMapE
	// ToIntMap convert any type to map of int.
	ToIntMap = complex.ToIntMap
	// ToIntMapE convert any type to map of int with error.
	ToIntMapE = complex.ToIntMapE
	// ToFloat64Map convert any type to map of float64.
	ToFloat64Map = complex.ToFloat64Map
	// ToFloat64MapE convert any type to map of float64 with error.
	ToFloat64MapE = complex.ToFloat64MapE

	// ToJSON convert any type to json.
	ToJSON = complex.ToJSON
	// ToJSONE convert any type to json with error.
	ToJSONE = complex.ToJSONE
	// FromJSON convert json to any type.
	FromJSON = complex.FromJSON
	// FromJSONE convert json to any type with error.
	FromJSONE = complex.FromJSONE
	// ToMapFromJSON convert json to map.
	ToMapFromJSON = complex.ToMapFromJSON
	// ToMapFromJSONE convert json to map with error.
	ToMapFromJSONE = complex.ToMapFromJSONE
	// ToSliceFromJSON convert json to slice.
	ToSliceFromJSON = complex.ToSliceFromJSON
	// ToSliceFromJSONE convert json to slice with error.
	ToSliceFromJSONE = complex.ToSliceFromJSONE
)
View Source
var (
	SetStringCacheSize = internal.SetStringCacheSize
	SetTimeCacheSize   = internal.SetTimeCacheSize
	ClearStringCache   = internal.ClearStringCache
	ClearTimeCache     = internal.ClearTimeCache
	ClearAllCaches     = internal.ClearAllCaches

	// Reflection cache
	SetTypeInfoCacheSize   = internal.SetTypeInfoCacheSize
	SetConversionCacheSize = internal.SetConversionCacheSize
	ClearTypeInfoCache     = internal.ClearTypeInfoCache
	ClearConversionCache   = internal.ClearConversionCache
)

Export cache related functions

Functions

This section is empty.

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL