Variable size/Get: Difference between revisions

Content added Content deleted
No edit summary
m (syntax highlighting fixup automation)
Line 6: Line 6:


=={{header|11l}}==
=={{header|11l}}==
<lang 11l>Int64 i
<syntaxhighlight lang="11l">Int64 i
print(T(i).size)
print(T(i).size)
print(Int64.size)</lang>
print(Int64.size)</syntaxhighlight>


{{out}}
{{out}}
Line 18: Line 18:
=={{header|ActionScript}}==
=={{header|ActionScript}}==
Requires the debug Flash Player 9.0.115.0 or higher.
Requires the debug Flash Player 9.0.115.0 or higher.
<syntaxhighlight lang="actionscript">
<lang ActionScript>
package {
package {
Line 51: Line 51:


}
}
</syntaxhighlight>
</lang>


=={{header|Ada}}==
=={{header|Ada}}==
Ada represents the size of a variable in bits, not bytes like many other languages.
Ada represents the size of a variable in bits, not bytes like many other languages.
<lang ada>Int_Bits : constant Integer := Integer'size;
<syntaxhighlight lang="ada">Int_Bits : constant Integer := Integer'size;
Whole_Bytes : constant Integer := Int_Bits / Storage_Unit; -- Storage_Unit is the number of bits per storage element</lang>
Whole_Bytes : constant Integer := Int_Bits / Storage_Unit; -- Storage_Unit is the number of bits per storage element</syntaxhighlight>


=={{header|ALGOL 68}}==
=={{header|ALGOL 68}}==
Line 68: Line 68:


Also note that the size of a '''byte''' can vary from one [[wp:CPU|CPU]] to another, c.f. [[Host_introspection#ALGOL_68]] for additional details.
Also note that the size of a '''byte''' can vary from one [[wp:CPU|CPU]] to another, c.f. [[Host_introspection#ALGOL_68]] for additional details.
<lang algol68>INT i; BYTES b; # typically INT and BYTES are the same size #
<syntaxhighlight lang="algol68">INT i; BYTES b; # typically INT and BYTES are the same size #
STRING s:="DCLXVI", [666]CHAR c;
STRING s:="DCLXVI", [666]CHAR c;
print((
print((
Line 74: Line 74:
"UPB STRING s =",UPB s, new line,
"UPB STRING s =",UPB s, new line,
"UPB []CHAR c =",UPB c, new line
"UPB []CHAR c =",UPB c, new line
))</lang>
))</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 83: Line 83:


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
<lang AutoHotkey>VarSetCapacity(Var, 10240000) ; allocate 10 megabytes
<syntaxhighlight lang="autohotkey">VarSetCapacity(Var, 10240000) ; allocate 10 megabytes
MsgBox % size := VarSetCapacity(Var) ; 10240000</lang>
MsgBox % size := VarSetCapacity(Var) ; 10240000</syntaxhighlight>


=={{header|Babel}}==
=={{header|Babel}}==
In Babel, you can get the raw size with the mu operator and you can also
In Babel, you can get the raw size with the mu operator and you can also
break this down into its components:
break this down into its components:
<lang babel>main:
<syntaxhighlight lang="babel">main:
{ (1 2 (3 4) 5 6)
{ (1 2 (3 4) 5 6)
dup mu disp
dup mu disp
Line 100: Line 100:


disp! : { %d cr << }
disp! : { %d cr << }
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 126: Line 126:
You can also take the size of an object by first serializing it:
You can also take the size of an object by first serializing it:


<lang babel>main : { (1 2 (3 4) 5 6) unload size %d << }
<syntaxhighlight lang="babel">main : { (1 2 (3 4) 5 6) unload size %d << }
</syntaxhighlight>
</lang>
{{out}}
{{out}}
38
38


=={{header|BASIC}}==
=={{header|BASIC}}==
<lang gwbasic>10 REM this only works with strings
<syntaxhighlight lang="gwbasic">10 REM this only works with strings
20 PRINT LEN(variable$)</lang>
20 PRINT LEN(variable$)</syntaxhighlight>


{{works with|QBasic}}
{{works with|QBasic}}
Line 139: Line 139:
Many BASICs, especially those compatible with [[QBasic]],
Many BASICs, especially those compatible with [[QBasic]],
can use <code>LEN</code> to find the size of any variable:
can use <code>LEN</code> to find the size of any variable:
<lang qbasic>DIM a AS INTEGER, b AS LONG, c AS SINGLE, d AS DOUBLE, e AS STRING
<syntaxhighlight lang="qbasic">DIM a AS INTEGER, b AS LONG, c AS SINGLE, d AS DOUBLE, e AS STRING
PRINT LEN(a), LEN(b), LEN(c), LEN(d), LEN(e)</lang>
PRINT LEN(a), LEN(b), LEN(c), LEN(d), LEN(e)</syntaxhighlight>


{{out}}
{{out}}
Line 151: Line 151:
<code>TypeOf</code> returns a number representing the type of value that was passed:
<code>TypeOf</code> returns a number representing the type of value that was passed:


<lang BASIC256>i = 1 #Integer
<syntaxhighlight lang="basic256">i = 1 #Integer
f = 1.0 #Float
f = 1.0 #Float
s$ = "cad" #String
s$ = "cad" #String
Line 162: Line 162:
print typeof(s$) # 3
print typeof(s$) # 3
print typeof(A) # 4
print typeof(A) # 4
print typeof(m) # 6</lang>
print typeof(m) # 6</syntaxhighlight>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
A variable's size is implied by its type suffix. The easiest way to determine the size is to use a structure:
A variable's size is implied by its type suffix. The easiest way to determine the size is to use a structure:
<lang bbcbasic> DIM bstruct{b&}
<syntaxhighlight lang="bbcbasic"> DIM bstruct{b&}
DIM istruct{i%}
DIM istruct{i%}
DIM fstruct{f}
DIM fstruct{f}
Line 177: Line 177:
PRINT "Size of f is ";DIM(fstruct{})
PRINT "Size of f is ";DIM(fstruct{})
PRINT "Size of d# is ";DIM(dstruct{})
PRINT "Size of d# is ";DIM(dstruct{})
PRINT "Size of s$ is ";DIM(sstruct{})</lang>
PRINT "Size of s$ is ";DIM(sstruct{})</syntaxhighlight>
Here the size given for the string s$ is for its descriptor, not its contents.
Here the size given for the string s$ is for its descriptor, not its contents.


Line 190: Line 190:


=={{header|C}}==
=={{header|C}}==
<lang c>printf("An int contains %u bytes.\n", sizeof(int));</lang>
<syntaxhighlight lang="c">printf("An int contains %u bytes.\n", sizeof(int));</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
<lang csharp>
<syntaxhighlight lang="csharp">
class Program
class Program
{
{
Line 203: Line 203:
}
}
}
}
</syntaxhighlight>
</lang>


=={{header|C++}}==
=={{header|C++}}==
Store the size of an int in bytes:
Store the size of an int in bytes:


<lang cpp>#include <cstdlib>
<syntaxhighlight lang="cpp">#include <cstdlib>
std::size_t intsize = sizeof(int);</lang>
std::size_t intsize = sizeof(int);</syntaxhighlight>


Note: sizeof can be used without the header <cstdlib>; the latter is only needed for the type std::size_t, which is an alias for whatever type is used to store sizes for the given compiler.
Note: sizeof can be used without the header <cstdlib>; the latter is only needed for the type std::size_t, which is an alias for whatever type is used to store sizes for the given compiler.


Output the number of bits of an int:
Output the number of bits of an int:
<lang cpp>#include <climits>
<syntaxhighlight lang="cpp">#include <climits>
#include <cstdlib>
#include <cstdlib>
std::size_t intbits = CHAR_BITS*sizeof(int);</lang>
std::size_t intbits = CHAR_BITS*sizeof(int);</syntaxhighlight>


Note: the type char is always 1 byte (which, however, need not be 8 bits).
Note: the type char is always 1 byte (which, however, need not be 8 bits).
Line 222: Line 222:
Get the size of a variable in bytes:
Get the size of a variable in bytes:


<lang cpp>#include <cstdlib>
<syntaxhighlight lang="cpp">#include <cstdlib>
int a = 1;
int a = 1;
std::size_t a_size = sizeof a;</lang>
std::size_t a_size = sizeof a;</syntaxhighlight>


Note: Parentheses are needed around types, but not around variables.
Note: Parentheses are needed around types, but not around variables.
Line 230: Line 230:
Get the size of an expression's type:
Get the size of an expression's type:


<lang cpp>#include <cstdlib>
<syntaxhighlight lang="cpp">#include <cstdlib>
std::size_t size = sizeof (3*6 + 7.5);</lang>
std::size_t size = sizeof (3*6 + 7.5);</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
Line 255: Line 255:
Directing Facility <code>>>IF P64 IS SET</code>, shown here.
Directing Facility <code>>>IF P64 IS SET</code>, shown here.
{{works with|GnuCOBOL}}
{{works with|GnuCOBOL}}
<syntaxhighlight lang="cobol">
<lang COBOL>
identification division.
identification division.
program-id. variable-size-get.
program-id. variable-size-get.
Line 317: Line 317:
goback.
goback.
end program variable-size-get.
end program variable-size-get.
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 377: Line 377:
{{works with|LispWorks}}
{{works with|LispWorks}}


<lang lisp>(let ((a (cons 1 2))
<syntaxhighlight lang="lisp">(let ((a (cons 1 2))
(b (make-array 10))
(b (make-array 10))
(c "a string"))
(c "a string"))
(list (hcl:find-object-size a)
(list (hcl:find-object-size a)
(hcl:find-object-size b)
(hcl:find-object-size b)
(hcl:find-object-size c)))</lang>
(hcl:find-object-size c)))</syntaxhighlight>
returns
returns


<lang lisp>(12 48 24)</lang>
<syntaxhighlight lang="lisp">(12 48 24)</syntaxhighlight>


However, note that interesting objects are generally composed of several levels of references, often including references to preexisting objects, so what the size should be considered as is often hard to define after the fact. A robust though non-automatic way to determine the “true” memory utilization of some data is to do something like this:
However, note that interesting objects are generally composed of several levels of references, often including references to preexisting objects, so what the size should be considered as is often hard to define after the fact. A robust though non-automatic way to determine the “true” memory utilization of some data is to do something like this:


<lang lisp>(let (items)
<syntaxhighlight lang="lisp">(let (items)
(gc) ; name varies by implementation
(gc) ; name varies by implementation
(room)
(room)
Line 395: Line 395:
(push (allocate-something-of-interest) items))
(push (allocate-something-of-interest) items))
(gc)
(gc)
(room))</lang>
(room))</syntaxhighlight>


[http://www.lispworks.com/documentation/HyperSpec/Body/f_room.htm room] prints information about current memory usage, but in an implementation-defined format. Take the difference of the relevant numbers, divide by 512, and you have the amount of memory consumed by allocating one additional instance of whatever it is.
[http://www.lispworks.com/documentation/HyperSpec/Body/f_room.htm room] prints information about current memory usage, but in an implementation-defined format. Take the difference of the relevant numbers, divide by 512, and you have the amount of memory consumed by allocating one additional instance of whatever it is.
Line 401: Line 401:
=={{header|D}}==
=={{header|D}}==
Every type and variable in D has a property <tt>sizeof</tt>, which give the size of the type in bytes. eg.
Every type and variable in D has a property <tt>sizeof</tt>, which give the size of the type in bytes. eg.
<lang d>int i ;
<syntaxhighlight lang="d">int i ;
writefln(i.sizeof) ; // print 4
writefln(i.sizeof) ; // print 4
int[13] ints1 ; // static integer array of length 13
int[13] ints1 ; // static integer array of length 13
Line 407: Line 407:
int[] ints2 = new int[13] ; // dynamic integer array, variable length, currently 13
int[] ints2 = new int[13] ; // dynamic integer array, variable length, currently 13
writefln(ints2.sizeof) ; // print 8, all dynamic array has this size
writefln(ints2.sizeof) ; // print 8, all dynamic array has this size
writefln(ints2.length) ; // print 13, length is the number of allocated element in aggregated type</lang>
writefln(ints2.length) ; // print 13, length is the number of allocated element in aggregated type</syntaxhighlight>


=={{header|Delphi}}==
=={{header|Delphi}}==
<lang delphi>i := sizeof({any variable or data type identifier});</lang>
<syntaxhighlight lang="delphi">i := sizeof({any variable or data type identifier});</syntaxhighlight>


=={{header|Elixir}}==
=={{header|Elixir}}==
When “counting” the number of elements in a data structure, Elixir also abides by a simple rule: the function is named '''size''' if the operation is in constant time or '''length''' if the operation is linear.
When “counting” the number of elements in a data structure, Elixir also abides by a simple rule: the function is named '''size''' if the operation is in constant time or '''length''' if the operation is linear.
<lang elixir>list = [1,2,3]
<syntaxhighlight lang="elixir">list = [1,2,3]
IO.puts length(list) #=> 3
IO.puts length(list) #=> 3


Line 435: Line 435:


map = Map.new([{:b, 1}, {:a, 2}])
map = Map.new([{:b, 1}, {:a, 2}])
IO.puts map_size(map) #=> 2</lang>
IO.puts map_size(map) #=> 2</syntaxhighlight>


=={{header|Erlang}}==
=={{header|Erlang}}==
Line 450: Line 450:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: layouts memory prettyprint ;
<syntaxhighlight lang="factor">USING: layouts memory prettyprint ;


! Show size in bytes
! Show size in bytes
Line 460: Line 460:


! Show number of bits in a fixnum
! Show number of bits in a fixnum
fixnum-bits . ! 60</lang>
fixnum-bits . ! 60</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
{{works with|ANS/ISO Forth}}
{{works with|ANS/ISO Forth}}
Forth is very close to the metal. Forth 94 standardized the size of an integer to be the native integer size of the CPU. Forth refers to this as a CELL. The defining word VARIABLE creates a variable that is one cell wide. The word CELLS takes an integer parameter and returns the number of bytes in one CELL.
Forth is very close to the metal. Forth 94 standardized the size of an integer to be the native integer size of the CPU. Forth refers to this as a CELL. The defining word VARIABLE creates a variable that is one cell wide. The word CELLS takes an integer parameter and returns the number of bytes in one CELL.
<lang Forth>: .CELLSIZE ( -- ) CR 1 CELLS . ." Bytes" ;
<syntaxhighlight lang="forth">: .CELLSIZE ( -- ) CR 1 CELLS . ." Bytes" ;
VARIABLE X ( creates a variable 1 cell wide)</lang>
VARIABLE X ( creates a variable 1 cell wide)</syntaxhighlight>
Test at the GNU Forth (32bit) console
Test at the GNU Forth (32bit) console
<lang forth>.CELLSIZE
<syntaxhighlight lang="forth">.CELLSIZE
4 Bytes ok
4 Bytes ok
-1 X ! ok
-1 X ! ok
HEX X @ U. FFFFFFFF ok</lang>
HEX X @ U. FFFFFFFF ok</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
The intrinsic functions bit_size and digits can be used to find the size of an integer. Bit_size returns the number of bits in an integer while digits returns the number of significant digits in the integer. Because of the use of signed integers this will be one less than the bit size. Digits can be used on real variables where it returns the number of significant figures in the mantissa.
The intrinsic functions bit_size and digits can be used to find the size of an integer. Bit_size returns the number of bits in an integer while digits returns the number of significant digits in the integer. Because of the use of signed integers this will be one less than the bit size. Digits can be used on real variables where it returns the number of significant figures in the mantissa.
<lang fortran>INTEGER, PARAMETER :: i8 = SELECTED_INT_KIND(2)
<syntaxhighlight lang="fortran">INTEGER, PARAMETER :: i8 = SELECTED_INT_KIND(2)
INTEGER, PARAMETER :: i16 = SELECTED_INT_KIND(4)
INTEGER, PARAMETER :: i16 = SELECTED_INT_KIND(4)
INTEGER, PARAMETER :: i32 = SELECTED_INT_KIND(8)
INTEGER, PARAMETER :: i32 = SELECTED_INT_KIND(8)
Line 489: Line 489:
WRITE (*,*) BIT_SIZE(fourbytes), DIGITS(fourbytes) ! prints 32 and 31
WRITE (*,*) BIT_SIZE(fourbytes), DIGITS(fourbytes) ! prints 32 and 31
WRITE (*,*) BIT_SIZE(eightbytes), DIGITS(eightbytes) ! prints 64 and 63
WRITE (*,*) BIT_SIZE(eightbytes), DIGITS(eightbytes) ! prints 64 and 63
WRITE (*,*) DIGITS(0.0), DIGITS(0d0) ! prints 24 and 53</lang>
WRITE (*,*) DIGITS(0.0), DIGITS(0d0) ! prints 24 and 53</syntaxhighlight>


=={{header|Free Pascal}}==
=={{header|Free Pascal}}==
Line 498: Line 498:


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Dim i As Integer
Dim i As Integer
Line 518: Line 518:
Print "Press any key to quit"
Print "Press any key to quit"
Sleep
Sleep
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 533: Line 533:
=={{header|Gambas}}==
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=87f102023bd9ef6dbd52b0158be2c3ee Click this link to run this code]'''
'''[https://gambas-playground.proko.eu/?gist=87f102023bd9ef6dbd52b0158be2c3ee Click this link to run this code]'''
<lang gambas>Public Sub Main()
<syntaxhighlight lang="gambas">Public Sub Main()


Print "Boolean =\t " & SizeOf(gb.Boolean)
Print "Boolean =\t " & SizeOf(gb.Boolean)
Line 548: Line 548:
Print "Variant =\t " & SizeOf(gb.Variant)
Print "Variant =\t " & SizeOf(gb.Variant)


End</lang>
End</syntaxhighlight>
Output:
Output:
<pre>
<pre>
Line 566: Line 566:


=={{header|Go}}==
=={{header|Go}}==
<lang go>import "unsafe"
<syntaxhighlight lang="go">import "unsafe"


unsafe.Sizeof(x)</lang>
unsafe.Sizeof(x)</syntaxhighlight>
More detail:
More detail:
<lang go>package main
<syntaxhighlight lang="go">package main


import (
import (
Line 594: Line 594:
// Some sizes are implementation dependent.
// Some sizes are implementation dependent.
fmt.Println(runtime.Version(), runtime.GOARCH)
fmt.Println(runtime.Version(), runtime.GOARCH)
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 606: Line 606:
=={{header|Haskell}}==
=={{header|Haskell}}==
only works with types that instance Storable:
only works with types that instance Storable:
<lang haskell>import Foreign
<syntaxhighlight lang="haskell">import Foreign


sizeOf (undefined :: Int) -- size of Int in bytes (4 on mine)
sizeOf (undefined :: Int) -- size of Int in bytes (4 on mine)
sizeOf (undefined :: Double) -- size of Double in bytes (8 on mine)
sizeOf (undefined :: Double) -- size of Double in bytes (8 on mine)
sizeOf (undefined :: Bool) -- size of Bool in bytes (4 on mine)
sizeOf (undefined :: Bool) -- size of Bool in bytes (4 on mine)
sizeOf (undefined :: Ptr a) -- size of Ptr in bytes (4 on mine)</lang>
sizeOf (undefined :: Ptr a) -- size of Ptr in bytes (4 on mine)</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
Line 623: Line 623:
** This will show 0 for the assignment of program constants such as strings. Manipulation will be required to produce an allocation.
** This will show 0 for the assignment of program constants such as strings. Manipulation will be required to produce an allocation.


<lang Icon>record rec0()
<syntaxhighlight lang="icon">record rec0()
record rec4(a,b,c,d)
record rec4(a,b,c,d)


Line 651: Line 651:
write("type=",type(x)," *x=",*x," bytes allocated=",a1-a0)
write("type=",type(x)," *x=",*x," bytes allocated=",a1-a0)
}
}
end</lang>
end</syntaxhighlight>


{{out}}
{{out}}
Line 674: Line 674:
IDL is array based, so its <tt>size()</tt> function is geared towards that:
IDL is array based, so its <tt>size()</tt> function is geared towards that:


<lang idl>arr = intarr(3,4)
<syntaxhighlight lang="idl">arr = intarr(3,4)
print,size(arr)
print,size(arr)
;=> prints this:
;=> prints this:
2 3 4 2 12</lang>
2 3 4 2 12</syntaxhighlight>


The result means: 2 dimensions in the array, the first dimension has extent 3, the second has extent 4, the elements of the array are 2-byte integers (IDL's default for an "int"), there's a total of 12 elements in the array.
The result means: 2 dimensions in the array, the first dimension has extent 3, the second has extent 4, the elements of the array are 2-byte integers (IDL's default for an "int"), there's a total of 12 elements in the array.
Line 686: Line 686:


For example:
For example:
<lang j>some_variable =: 42
<syntaxhighlight lang="j">some_variable =: 42
7!:5<'some_variable'</lang>
7!:5<'some_variable'</syntaxhighlight>
An advantage of <code>7!:5</code> is that it can be used on any name, including functions, operators, etc (i.e. it's not just restricted to variables):
An advantage of <code>7!:5</code> is that it can be used on any name, including functions, operators, etc (i.e. it's not just restricted to variables):
<lang j>some_function =: +/ % #
<syntaxhighlight lang="j">some_function =: +/ % #
7!:5<'some_function'</lang>
7!:5<'some_function'</syntaxhighlight>


=={{header|Julia}}==
=={{header|Julia}}==
<lang julia>julia> sizeof(Int8)
<syntaxhighlight lang="julia">julia> sizeof(Int8)
1
1


Line 700: Line 700:


julia> sizeof(t)
julia> sizeof(t)
8</lang>
8</syntaxhighlight>
(The last line returns 4 on a 32-bit machine or when Julia is compiled in 32-bit mode.)
(The last line returns 4 on a 32-bit machine or when Julia is compiled in 32-bit mode.)


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<lang scala>// version 1.1.2
<syntaxhighlight lang="scala">// version 1.1.2


fun main(args: Array<String>) {
fun main(args: Array<String>) {
Line 715: Line 715:
println("A Double variable occupies: ${java.lang.Double.SIZE / 8} bytes")
println("A Double variable occupies: ${java.lang.Double.SIZE / 8} bytes")
println("A Char variable occupies: ${java.lang.Character.SIZE / 8} bytes")
println("A Char variable occupies: ${java.lang.Character.SIZE / 8} bytes")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 729: Line 729:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang Lasso>local(
<syntaxhighlight lang="lasso">local(
mystring = 'Hello World',
mystring = 'Hello World',
myarray = array('one', 'two', 3),
myarray = array('one', 'two', 3),
Line 750: Line 750:
//#myinteger -> size // will fail
//#myinteger -> size // will fail
// an integer can however be converted to a string first
// an integer can however be converted to a string first
string(#myinteger) -> size</lang>
string(#myinteger) -> size</syntaxhighlight>
->11
->11


Line 759: Line 759:
4
4
=={{header|Lua}}==
=={{header|Lua}}==
<lang lua>> s = "hello"
<syntaxhighlight lang="lua">> s = "hello"
> print(#s)
> print(#s)
5
5
> t = { 1,2,3,4,5 }
> t = { 1,2,3,4,5 }
> print(#t)
> print(#t)
5</lang>
5</syntaxhighlight>


=={{header|Mathematica}}/{{header|Wolfram Language}}==
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<lang Mathematica>ByteCount["somerandomstring"]</lang>
<syntaxhighlight lang="mathematica">ByteCount["somerandomstring"]</syntaxhighlight>
{{out}}
{{out}}
<pre>64</pre>
<pre>64</pre>
Line 774: Line 774:
BITSIZE and BYTESIZE are built in functions.
BITSIZE and BYTESIZE are built in functions.


<lang modula3>MODULE Size EXPORTS Main;
<syntaxhighlight lang="modula3">MODULE Size EXPORTS Main;


FROM IO IMPORT Put;
FROM IO IMPORT Put;
Line 782: Line 782:
Put("Integer in bits: " & Int(BITSIZE(INTEGER)) & "\n");
Put("Integer in bits: " & Int(BITSIZE(INTEGER)) & "\n");
Put("Integer in bytes: " & Int(BYTESIZE(INTEGER)) & "\n");
Put("Integer in bytes: " & Int(BYTESIZE(INTEGER)) & "\n");
END Size.</lang>
END Size.</syntaxhighlight>


{{out}}
{{out}}
Line 791: Line 791:


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>echo "An int contains ", sizeof(int), " bytes."</lang>
<syntaxhighlight lang="nim">echo "An int contains ", sizeof(int), " bytes."</syntaxhighlight>


=={{header|NS-HUBASIC}}==
=={{header|NS-HUBASIC}}==
Note: This only works with strings.
Note: This only works with strings.
<lang NS-HUBASIC>10 PRINT LEN(VARIABLE$)</lang>
<syntaxhighlight lang="ns-hubasic">10 PRINT LEN(VARIABLE$)</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>(** The result is the size given in word.
<syntaxhighlight lang="ocaml">(** The result is the size given in word.
The word size in octet can be found with (Sys.word_size / 8).
The word size in octet can be found with (Sys.word_size / 8).
(The size of all the datas in OCaml is at least one word, even chars and bools.)
(The size of all the datas in OCaml is at least one word, even chars and bools.)
Line 822: Line 822:
in
in
fst(rec_size [] (Obj.repr v))
fst(rec_size [] (Obj.repr v))
;;</lang>
;;</syntaxhighlight>


testing in the toplevel:
testing in the toplevel:
<lang ocaml># sizeof 234 ;;
<syntaxhighlight lang="ocaml"># sizeof 234 ;;
- : int = 1
- : int = 1


Line 909: Line 909:


# sizeof(Array.init 10 (fun _ -> String.create 20)) ;;
# sizeof(Array.init 10 (fun _ -> String.create 20)) ;;
- : int = 61</lang>
- : int = 61</syntaxhighlight>


=={{header|Ol}}==
=={{header|Ol}}==
Line 925: Line 925:
=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
In GP, this gets the size of the variable x in bytes:
In GP, this gets the size of the variable x in bytes:
<lang parigp>sizebyte(x)</lang>
<syntaxhighlight lang="parigp">sizebyte(x)</syntaxhighlight>


In PARI,
In PARI,
<lang C>lg(x)</lang>
<syntaxhighlight lang="c">lg(x)</syntaxhighlight>
returns the length of the variable x in words. <code>gsizebyte</code> and <code>gsizeword</code> are also available.
returns the length of the variable x in words. <code>gsizebyte</code> and <code>gsizeword</code> are also available.


Line 938: Line 938:
{{works with|Perl|5.28}}
{{works with|Perl|5.28}}
{{libheader|Devel::Size}}
{{libheader|Devel::Size}}
<lang perl>use Devel::Size qw(size total_size);
<syntaxhighlight lang="perl">use Devel::Size qw(size total_size);


my $var = 9384752;
my $var = 9384752;
my @arr = (1, 2, 3, 4, 5, 6);
my @arr = (1, 2, 3, 4, 5, 6);
print size($var); # 24
print size($var); # 24
print total_size(\@arr); # 256</lang>
print total_size(\@arr); # 256</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"An integer contains %d bytes.\n"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">machine_word</span><span style="color: #0000FF;">())</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"An integer contains %d bytes.\n"</span><span style="color: #0000FF;">,</span> <span style="color: #7060A8;">machine_word</span><span style="color: #0000FF;">())</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
See builtins\VM\pHeap.e for the complete low-level details. Because of shared references,
See builtins\VM\pHeap.e for the complete low-level details. Because of shared references,
it is often not practical to obtain a meaningful size, and you can often store a "sparse"
it is often not practical to obtain a meaningful size, and you can often store a "sparse"
Line 966: Line 966:


=={{header|PL/I}}==
=={{header|PL/I}}==
<syntaxhighlight lang="pl/i">
<lang PL/I>
put skip list (SIZE(x)); /* gives the number of bytes occupied by X */
put skip list (SIZE(x)); /* gives the number of bytes occupied by X */
/* whatever data type or structure it is. */
/* whatever data type or structure it is. */
Line 975: Line 975:
/* varying-length string, including its */
/* varying-length string, including its */
/* length field. */
/* length field. */
</syntaxhighlight>
</lang>


=={{header|Pop11}}==
=={{header|Pop11}}==
Line 983: Line 983:
Form user point of view more important is space taken by values (size of values referenced by a single variable typically varies during program execution). The datasize function gives amount (in machine words) of space directly used by given value:
Form user point of view more important is space taken by values (size of values referenced by a single variable typically varies during program execution). The datasize function gives amount (in machine words) of space directly used by given value:


<lang pop11>;;; Prints 0 because small integers need no heap storage
<syntaxhighlight lang="pop11">;;; Prints 0 because small integers need no heap storage
datasize(12) =>
datasize(12) =>
;;; Prints 3: 3 character fits into single machine word, 1 word
;;; Prints 3: 3 character fits into single machine word, 1 word
Line 992: Line 992:
datasize({1 2 3}) =>
datasize({1 2 3}) =>
;;; Prints 3 because only first node counts
;;; Prints 3 because only first node counts
datasize([1 2 3]) =></lang>
datasize([1 2 3]) =></syntaxhighlight>


Note that large amount of data my be referenced from given value, but this data is potentially shared, so there is no canonical way to assign it to a single value or variable.
Note that large amount of data my be referenced from given value, but this data is potentially shared, so there is no canonical way to assign it to a single value or variable.


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Define a
<syntaxhighlight lang="purebasic">Define a
Debug SizeOf(a)
Debug SizeOf(a)
; This also works for structured variables</lang>
; This also works for structured variables</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
This information is only easily available for the array type:
This information is only easily available for the array type:
<lang python>>>> from array import array
<syntaxhighlight lang="python">>>> from array import array
>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'),
>>> argslist = [('l', []), ('c', 'hello world'), ('u', u'hello \u2641'),
('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]
('l', [1, 2, 3, 4, 5]), ('d', [1.0, 2.0, 3.14])]
Line 1,017: Line 1,017:
array('l', [1, 2, 3, 4, 5]) Size = 20
array('l', [1, 2, 3, 4, 5]) Size = 20
array('d', [1.0, 2.0, 3.1400000000000001]) Size = 24
array('d', [1.0, 2.0, 3.1400000000000001]) Size = 24
>>></lang>
>>></syntaxhighlight>
Also:
Also:
{{works with|Python|2.6+}}
{{works with|Python|2.6+}}
<lang python>import sys
<syntaxhighlight lang="python">import sys
sys.getsizeof(obj)</lang>
sys.getsizeof(obj)</syntaxhighlight>


=={{header|R}}==
=={{header|R}}==
object.size gives '''an estimate''' of the amount of memory used to store the variable, in (kilo/Mega/Giga) bytes. See also dim, length and nchar for determining the extent of mulitdimensional variables (such as matrices, lists, etc).
object.size gives '''an estimate''' of the amount of memory used to store the variable, in (kilo/Mega/Giga) bytes. See also dim, length and nchar for determining the extent of mulitdimensional variables (such as matrices, lists, etc).
<lang R># Results are system dependent
<syntaxhighlight lang="r"># Results are system dependent
num <- c(1, 3, 6, 10)
num <- c(1, 3, 6, 10)
object.size(num) # e.g. 56 bytes
object.size(num) # e.g. 56 bytes
Line 1,038: Line 1,038:


l2 <- list(num, num2)
l2 <- list(num, num2)
object.size(l2) # e.g. 128 bytes</lang>
object.size(l2) # e.g. 128 bytes</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>
<syntaxhighlight lang="racket">
#lang racket
#lang racket
(require ffi/unsafe)
(require ffi/unsafe)
Line 1,047: Line 1,047:
(begin (printf "sizeof(~a) = ~a\n" 't (ctype-sizeof t)) ...))
(begin (printf "sizeof(~a) = ~a\n" 't (ctype-sizeof t)) ...))
(sizes _byte _short _int _long _llong _float _double)
(sizes _byte _short _int _long _llong _float _double)
</syntaxhighlight>
</lang>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
Raku tries to avoid generic terms such as "size" and "length", instead providing methods that are expressed in terms of the units appropriate to the abstraction level.
Raku tries to avoid generic terms such as "size" and "length", instead providing methods that are expressed in terms of the units appropriate to the abstraction level.
<lang perl6># Textual strings are measured in characters (graphemes)
<syntaxhighlight lang="raku" line># Textual strings are measured in characters (graphemes)
my $string = "abc";
my $string = "abc";


Line 1,063: Line 1,063:
my $buffer = '#56997; means "four dragons".'.encode('utf8');
my $buffer = '#56997; means "four dragons".'.encode('utf8');
say $buffer.bytes; # 26
say $buffer.bytes; # 26
say $buffer.elems; # 26</lang>
say $buffer.elems; # 26</syntaxhighlight>
Raku's Int type is arbitrary sized, and therefore the abstract size of the integer depends on how many bits are needed to represent it. While the internal representation is likely to be "chunky" by 32 or 64 bits, this is considered an implementation detail and is not revealed to the programmer.
Raku's Int type is arbitrary sized, and therefore the abstract size of the integer depends on how many bits are needed to represent it. While the internal representation is likely to be "chunky" by 32 or 64 bits, this is considered an implementation detail and is not revealed to the programmer.


Line 1,071: Line 1,071:
In REXX, you simply set a variable to a value (it could be an expression);
In REXX, you simply set a variable to a value (it could be an expression);
<br>the value's length is the size of the variable's value.
<br>the value's length is the size of the variable's value.
<lang rexx>/*REXX program demonstrates (see the penultimate statement) how to */
<syntaxhighlight lang="rexx">/*REXX program demonstrates (see the penultimate statement) how to */
/* to find the size (length) of the value of a REXX variable. */
/* to find the size (length) of the value of a REXX variable. */


Line 1,130: Line 1,130:
│ The "k" loop uses 21,777,792 bytes for the compound variables, │
│ The "k" loop uses 21,777,792 bytes for the compound variables, │
│ (excluding the DO loop indices [j and k] themselves). │
│ (excluding the DO loop indices [j and k] themselves). │
└────────────────────────────────────────────────────────────────────┘*/</lang>
└────────────────────────────────────────────────────────────────────┘*/</syntaxhighlight>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
list1 = list(2)
list1 = list(2)
list2 = list(4)
list2 = list(4)
Line 1,145: Line 1,145:
see "Size of list4 is : " + len(list4) + nl
see "Size of list4 is : " + len(list4) + nl
see "Size of list5 is : " + len(list5) + nl
see "Size of list5 is : " + len(list5) + nl
</syntaxhighlight>
</lang>
Output:
Output:
<pre>
<pre>
Line 1,158: Line 1,158:
Almost all objects in Ruby (MRI) take 40 bytes (on a x64 machine) initially. Sometimes this is enough to store the entire object, sometimes additional memory has to be allocated. For strings that is the case if they are longer than 23 chars. The additional memory can be retrieved using 'ObjectSpace':
Almost all objects in Ruby (MRI) take 40 bytes (on a x64 machine) initially. Sometimes this is enough to store the entire object, sometimes additional memory has to be allocated. For strings that is the case if they are longer than 23 chars. The additional memory can be retrieved using 'ObjectSpace':


<lang ruby>
<syntaxhighlight lang="ruby">
require 'objspace'
require 'objspace'


Line 1,164: Line 1,164:
p ObjectSpace.memsize_of("a"*24) #=> 25
p ObjectSpace.memsize_of("a"*24) #=> 25
p ObjectSpace.memsize_of("a"*1000) #=> 1001
p ObjectSpace.memsize_of("a"*1000) #=> 1001
</syntaxhighlight>
</lang>


=={{header|Rust}}==
=={{header|Rust}}==
<lang Rust>use std::mem;
<syntaxhighlight lang="rust">use std::mem;


fn main() {
fn main() {
Line 1,177: Line 1,177:
assert_eq!(6, mem::size_of_val(&arr));
assert_eq!(6, mem::size_of_val(&arr));
}
}
</syntaxhighlight>
</lang>


=={{header|Scala}}==
=={{header|Scala}}==
{{libheader|Scala}}<lang Scala> def nBytes(x: Double) = ((Math.log(x) / Math.log(2) + 1e-10).round + 1) / 8
{{libheader|Scala}}<syntaxhighlight lang="scala"> def nBytes(x: Double) = ((Math.log(x) / Math.log(2) + 1e-10).round + 1) / 8


val primitives: List[(Any, Long)] =
val primitives: List[(Any, Long)] =
Line 1,188: Line 1,188:
(Long, Long.MaxValue))
(Long, Long.MaxValue))


primitives.foreach(t => println(f"A Scala ${t._1.toString.drop(13)}%-5s has ${nBytes(t._2)} bytes"))</lang>
primitives.foreach(t => println(f"A Scala ${t._1.toString.drop(13)}%-5s has ${nBytes(t._2)} bytes"))</syntaxhighlight>
{{out}}
{{out}}
<pre>A Scala Byte has 1 bytes
<pre>A Scala Byte has 1 bytes
Line 1,196: Line 1,196:


=={{header|Swift}}==
=={{header|Swift}}==
<lang swift>sizeofValue(x)</lang>
<syntaxhighlight lang="swift">sizeofValue(x)</syntaxhighlight>
More detail:
More detail:
<lang swift>// sizeof and sizeofValue return the size in bytes.
<syntaxhighlight lang="swift">// sizeof and sizeofValue return the size in bytes.
println(sizeof(Int))
println(sizeof(Int))
var i: Int = 42
var i: Int = 42
Line 1,206: Line 1,206:
// the same number, the size of the String struct.
// the same number, the size of the String struct.
println(sizeofValue("Rosetta"))
println(sizeofValue("Rosetta"))
println(sizeofValue("Code"))}</lang>
println(sizeofValue("Code"))}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,217: Line 1,217:
=={{header|Tcl}}==
=={{header|Tcl}}==
Since all variables are ultimately strings in Tcl, this is easy:
Since all variables are ultimately strings in Tcl, this is easy:
<lang tcl>string bytelength $var</lang>
<syntaxhighlight lang="tcl">string bytelength $var</syntaxhighlight>
There is additional overhead per value and per variable, which depends on the architecture that Tcl was built for and the version of Tcl. In 8.5 on a ILP-32 architecture, local variables have an overhead of 8 bytes (without traces) and values have a minimum overhead of 24 bytes (this minimum is achieved for integers that fit in a signed 64-bit integer type or a double-precision float).
There is additional overhead per value and per variable, which depends on the architecture that Tcl was built for and the version of Tcl. In 8.5 on a ILP-32 architecture, local variables have an overhead of 8 bytes (without traces) and values have a minimum overhead of 24 bytes (this minimum is achieved for integers that fit in a signed 64-bit integer type or a double-precision float).


Line 1,225: Line 1,225:
There are two primary data types in Toka, cells and characters. The size of these can be obtained easily:
There are two primary data types in Toka, cells and characters. The size of these can be obtained easily:


<lang toka>char-size .
<syntaxhighlight lang="toka">char-size .
cell-size .</lang>
cell-size .</syntaxhighlight>


If you load the floating point support, you can also obtain the size of a floating point number:
If you load the floating point support, you can also obtain the size of a floating point number:


<lang toka>needs floats
<syntaxhighlight lang="toka">needs floats
float-size .</lang>
float-size .</syntaxhighlight>


All sizes are returned in bytes.
All sizes are returned in bytes.


=={{header|TUSCRIPT}}==
=={{header|TUSCRIPT}}==
<lang tuscript>
<syntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT,{}
$$ MODE TUSCRIPT,{}
string="somerandomstring"
string="somerandomstring"
Line 1,245: Line 1,245:
PRINT "has size: ",size
PRINT "has size: ",size
PRINT "and length: ",length
PRINT "and length: ",length
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,299: Line 1,299:
The <code>struct</code> size corresponds to the size of the C struct
The <code>struct</code> size corresponds to the size of the C struct


<lang c>struct foo {
<syntaxhighlight lang="c">struct foo {
uint32_t x : 17;
uint32_t x : 17;
uint8_t y : 3;
uint8_t y : 3;
char z[16];
char z[16];
};</lang>
};</syntaxhighlight>


as calculated by the GNU C compiler on the same platform. The `uint32_t` leading bitfield creates a minimum alignment of four bytes. The `y` bitfield is packed into the third byte of the structure, and the `z` array starts on the fourth, ending on the nineteenth. The alignment requirement pads the structure to 20.
as calculated by the GNU C compiler on the same platform. The `uint32_t` leading bitfield creates a minimum alignment of four bytes. The `y` bitfield is packed into the third byte of the structure, and the `z` array starts on the fourth, ending on the nineteenth. The alignment requirement pads the structure to 20.
Line 1,331: Line 1,331:
=={{header|UNIX Shell}}==
=={{header|UNIX Shell}}==


<lang sh># In the shell all variables are stored as strings, so we use the same technique
<syntaxhighlight lang="sh"># In the shell all variables are stored as strings, so we use the same technique
# as for finding the length of a string:
# as for finding the length of a string:
greeting='Hello, world!'
greeting='Hello, world!'
greetinglength=`printf '%s' "$greeting" | wc -c`
greetinglength=`printf '%s' "$greeting" | wc -c`
echo "The greeting is $greetinglength characters in length"</lang>
echo "The greeting is $greetinglength characters in length"</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
Line 1,351: Line 1,351:
and returns the number of bits of precision in the mantissa.
and returns the number of bits of precision in the mantissa.
Host memory usage is linear plus a small constant.
Host memory usage is linear plus a small constant.
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std


#cast %nL
#cast %nL


examples = <weight 'hello',mpfr..prec 1.0E+0></lang>
examples = <weight 'hello',mpfr..prec 1.0E+0></syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,362: Line 1,362:


=={{header|Vala}}==
=={{header|Vala}}==
<lang vala>void main(){
<syntaxhighlight lang="vala">void main(){
/* you can replace the int below with any of the vala supported datatypes
/* you can replace the int below with any of the vala supported datatypes
see the vala documentation for valid datatypes.
see the vala documentation for valid datatypes.
*/
*/
print(@"$(sizeof(int))\n");
print(@"$(sizeof(int))\n");
}</lang>
}</syntaxhighlight>


=={{header|Vlang}}==
=={{header|Vlang}}==
<lang>sizeof(i64)</lang>
<syntaxhighlight lang="text">sizeof(i64)</syntaxhighlight>
{{out}}
{{out}}
<pre>8</pre>
<pre>8</pre>
Line 1,381: Line 1,381:
=={{header|Yabasic}}==
=={{header|Yabasic}}==
<code>frnfn_size</code> return the size (in bytes) of one of the types available for foreign function calls.
<code>frnfn_size</code> return the size (in bytes) of one of the types available for foreign function calls.
<lang yabasic>print frnfn_size("uint8") //1
<syntaxhighlight lang="yabasic">print frnfn_size("uint8") //1
print frnfn_size("int8") //1
print frnfn_size("int8") //1
print frnfn_size("uint16") //2
print frnfn_size("uint16") //2
Line 1,393: Line 1,393:
print frnfn_size("char") //1
print frnfn_size("char") //1
print frnfn_size("int") //4
print frnfn_size("int") //4
print frnfn_size("short") //2</lang>
print frnfn_size("short") //2</syntaxhighlight>


=={{header|XPL0}}==
=={{header|XPL0}}==
Line 1,407: Line 1,407:
for dynamic integer arrays using the Reserve intrinsic.
for dynamic integer arrays using the Reserve intrinsic.


<lang XPL0>include c:\cxpl\codes;
<syntaxhighlight lang="xpl0">include c:\cxpl\codes;
int Size;
int Size;
int A, B;
int A, B;
Line 1,415: Line 1,415:
Size:= addr Y - addr X;
Size:= addr Y - addr X;
IntOut(0, Size); CrLf(0);
IntOut(0, Size); CrLf(0);
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 1,424: Line 1,424:


=={{header|zkl}}==
=={{header|zkl}}==
<lang zkl>(123).len() //-->1 (byte)
<syntaxhighlight lang="zkl">(123).len() //-->1 (byte)
(0).MAX.len() //-->8 (bytes), ie the max number of bytes in an int
(0).MAX.len() //-->8 (bytes), ie the max number of bytes in an int
(1.0).MAX.len() //-->8 (bytes), ie the max number of bytes in an float
(1.0).MAX.len() //-->8 (bytes), ie the max number of bytes in an float
Line 1,431: Line 1,431:
Dictionary("1",1, "2",2).len() //-->2 (keys)
Dictionary("1",1, "2",2).len() //-->2 (keys)
Data(0,Int,1,2,3,4).len() //-->4 (bytes)
Data(0,Int,1,2,3,4).len() //-->4 (bytes)
Data(0,String,"1","2","3","4").len() //-->8 bytes (ASCIIZ)</lang>
Data(0,String,"1","2","3","4").len() //-->8 bytes (ASCIIZ)</syntaxhighlight>


Put the data into a variable, same results: a:=123; a.len() --> 1
Put the data into a variable, same results: a:=123; a.len() --> 1