"in java, is it more efficient to use byte or short instead of int and float instead of double?" Code Answer
Answers related to “in java, is it more efficient to use byte or short instead of int and float instead of double?”
- When inserting an entity with associations, is there a way to just use the FK instead of retrieving the entity?
- Is it bad practice to use variable variables in PHP?
- Is it bad practice to use dot notation in Mustache (php)?
- Why is it frowned upon to use a null layout in Swing?
- Java using much more memory than heap size (or size correctly Docker memory limit)
- Is there an advantage to use a Synchronized Method instead of a Synchronized Block?
- How to use Scanner to accept only valid int as input
- In Java, is the result of the addition of two chars an int or a char?
- How to make the division of 2 ints produce a float instead of another int?
- Why is it not advisable to use attach() in R, and what should I use instead?
- It is a bad practice to use Sun's proprietary Java classes?
- Java JDBC - How to connect to Oracle using Service Name instead of SID
- In Java, how do I convert a byte array to a string of hex digits while keeping leading zeros?
- When exactly is it leak safe to use (anonymous) inner classes?
- Is there a way to use Selenium WebDriver without informing the document that it is controlled by WebDriver?
- It is more efficient to use if-return-return or if-else-return?
- In C++, is it safe/portable to use static member function pointer for C API callbacks?
- Why does the Java API use int instead of short or byte?
- Is it better practice to use String.format over string Concatenation in Java?
- How to use the unsigned Integer in Java 8 and Java 9?
- Why we use if, else if instead of multiple if block if the body is a return statement
- In Java, is it possible to know whether a class has already been loaded?
- Is it bad practice to use a built-in function name as an attribute or method identifier?
- What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure...
- Why is it not possible to extend annotations in Java?
- Is it wrong to use Deprecated methods or classes in Java?
- Is it ever advantageous to use 'goto' in a language that supports loops and functions? If so, why?
- Is it good practice to use java.lang.String.intern()?
- Why is it a bad practice to return generated HTML instead of JSON? Or is it?
- Is it possible to create an “uber” jar containing the project classes and the project dependencies as jars with a...
- Is it bad practice to use Reflection in Unit testing?
- How to use python numpy.savetxt to write strings and float number to an ASCII file?
- Whats the use of saying <? extends SomeObject> instead of <SomeObject>
- How to use Selenium WebDriver on local webpage (on my PC) instead of one located somewhere online?
- In Java is it possible to re-open System.in after closing it
- Is it bad practice to use inline event handlers in HTML? [closed]
- Is it good practice to use ordinal of enum? [closed]
- Is it bad practice to use break to exit a loop in Java? [closed]
- Is it ok to assign the JavaScript prototype object instead of just its properties?
- Is it possible to build a java project only once using eclipse and share?
- Is it possible to create a type in c++ that takes less than one byte of memory?
- In Java, is using throws Exception instead of throwing multiple specific exceptions good practice?
- Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?
- How to use JPA2's @Cacheable instead of Hibernate's @Cache
- Which one to use, int or Integer
- How do you construct a LINQ to Entities query to load child objects directly, instead of calling a Reference...
- Calling a getter in Java though reflection: What's the fastest way to repeatedly call it (performance and...
- Whether to use invokeAll or submit - java Executor service
- How to use “Static factory methods” instead of constructors?
- In Perl, is it appropriate to use map in void context instead of a foreach loop?
- java: Is it possible to set a lambda expression for an array of Buttons is a for loop? If so how?
- String to Int in java - Likely bad data, need to avoid exceptions
- How is it possible to create a spinner with images instead of text?
- Is there a way to use maven property in Java class during compilation
- Is it possible in Java to check if objects fields are null and then add default value to all those attributes?
- Is it safe not to close a Java Scanner, provided I close the underlying readable?
- Is it correct way to use ModelState.Remove to deal with ModelState?
- Is it good practice to use assert in Java?
- Why are there no byte or short literals in Java?
- When is it necessary/appropriate to use InAttribute and OutAttribute for COM Interop
- jQuery - how to use the “on()” method instead of “live()”?
- how to use python2.7 pip instead of default pip
- Size of int and sizeof int pointer on a 64 bit machine
- Is it expensive/efficient to send data between processes in Node?
- In C# would it be better to use Queue.Synchronized or lock() for thread safety?
- How to read the full stacktrace in Java where it says e.g. “… 23 more”
- In Hibernate: is it possible to mix Annotations and XML configuration for an Entity?
- JAXB compiler is binding xs:boolean to Java Boolean wrapper class, instead of boolean primitive type
- Is it more Pythonic to use String Formatting over String Concatenation in Python 3?
- What is it called when you use object… as a parameter?
- Is it more efficient to preallocate a vector?
- Is it better to use a TreeSet or ArrayList when using a custom comparator
- Is it more efficient to perform a range check by casting to uint instead of checking for negative values?
- When to use Enum or Collection in Java
- How to use numpy with OpenBLAS instead of Atlas in Ubuntu?
- When to use TEXT in mysql instead of VARCHAR
- Is there a way to use java.util.Preferences under Windows without it using the Registry as the backend?
- Is there a way to use annotations in Java to replace accessors?
- In Java, is it safe to change a reference to a HashMap read concurrently
- How to use mllib.recommendation if the user ids are string instead of contiguous integers?
- Is it good practice to use serialize in PHP in order to store data into the DB?
- Can I force the browser to use CSS @font-face instead of font installed on system?
- Is it possible to change IntelliJ's code generation template for equals() and hashCode()
- Is there a standard in java for _ (underscore) in front of variable or class names?
- In Java is it possible to create a type-safe Map of classes to instances of their class?
- Is it always better to use 'DbContext' instead of 'ObjectContext'?
- Why it is a bad practice to use break/continue labels in OOP (e.g. Java, C#)? [closed]
- Any reason to use a Git alias instead of a git-* script?
- How to use SimplexSolver or SimplexOptimizer in java apache math?
- Comparing Performance of int and Integer
- Is it good idea to use uint instead of int as the primary key in data model class?
- Compile c code with float instead of double
- Is there no way to iterate over or copy all the values of a Java ThreadLocal?
- Is it possible to declare two wildcard types to be of same type?
- Java indexOf function more efficient than Rabin-Karp? Search Efficiency of Text
- Why is it not allowed to narrow down scope of a method while overriding
- In React is it always better to render a Redirect than use this.props.history.push?
- Java - Is it possible to subclass an array? And more questions about arrays in Java
- Is @Produces more efficient that a getter in an EL expression
- Get TinyMCE to use full image url instead of relative one
- Why do we need to use virtual ~A() = default; instead of virtual ~A() {} in C++11?
- Is it possible to invoke private attributes or methods via reflection
- In vim, is there a plugin to use % to match the corresponding double quote (")?
- Is it currently possible to build Eclipse Plugins by Maven AND have nice IDE Integration?
- Why do we have to use the __dunder__ methods instead of operators when calling via super?
- Is it possible/right to use multiple @Html.AntiForgeryToken() in 2 different forms in one page?
- Can anyone give me a REALLY good reason to use CLR type names instead of C# type names (aliases) in code (as a...
- Is it possible to make eclipse generate hashCode and equals with HashCodeBuilder and EqualsBuilder
- Is it always faster to use string as key in a dict?
- Why is it not possible to use the MPMoviePlayerController more than once?
- Java: Is it possible to always execute a certain function before other functions are called? (Like @Before in JUnit)
- Is it good practice to use size_t in C++?
- Type conversion of int and string, java
- Is there a way to get, at runtime, the version of Guava in use?
- Create array of incremental int using Stream instead of for loop
- When does Python perform type conversion when comparing int and float?
- How to use tf.layers classes instead of functions
- Is it possible to rotate characters of a word instead of rotating the whole word using css3
- Java Web Service returns string with > and < instead of > and <
- Unexpected result while dividing int by int and storing result into double
- Is it possible to configure Guava Cache (or other library) behaviour to be: If time to reload, return previous...
- Why does Java ArrayList use per-element casting instead of per-array casting?
- How to specify a constant is a byte or short?
- In which case it is better to use the .append(), and which .appendTo()?
- Is it not possible to use HTML entities in a title attribute?
- For Array, is it more efficient to use map() & reduce() instead of forEach() in javascript?
- JAVA: Is it possible to use a variable outside a loop that has been initialised inside a loop?
- How to use Pooled Spring beans instead of Singleton ones?
- Is it ok to save JavaVM * and JNIEnv * as a global variable and use it elsewhere?
- How the byte range is -128 to 127 in java.How it is possible?
- Is it faster to connect/use MySQL at localhost instead of a domain (even if the domain resolves to the same computer)?
- In C#, is it more performant to use fully qualified names vs the 'using' directive?
- In Java: is where a way to create a subarray that will point to a portion of a bigger array?
- How can I get authlogic to use the Rails session instead of its own cookie?
- Is it okay for a class to have a field of its own type
- In Java is it possible to change or modify an enum itself and thus to corrupt an enum singleton?
- Is it Better practice to Declare individual objects or loop Anonymous objects into ArrayList?
- Behavior of int and short in c
- Why is it not possible to use “Using static” feature with private enum? Is there any alternative?
- Is it possible to extract metadata from fetched url instead of canonical url?
- Can we use generic to allow only specific types instead of any type <T>?
- Is it possible to create dynamic Bindings.OR in JavaFX?
- Is it good practice to use @Produces(“application/json”) on all JSON producing endpoints?
- My query is taking too long to finish for finding the pair of rows where the difference of columns value is maximum...
- How to get data from JSP to Action class by id instead of property in Struts 2?
- In this example, why is it still necessary to typecast an object to be sure of its type, even after getClass() has...
- How to sort data by date in java before storing into an array of object or from list which contains object...
- is it possible to define execution order for a set of threads in java
- Why are people continuing to use xml mapping files instead of annotations? [closed]
- When to use []byte or string in Go?
- Is it possible to use 'yield' to generate 'Iterator' instead of a list in Scala?
- Why use abs() or fabs() instead of conditional negation?
- Is it possible to use `keyof` operator on literals instead of interfaces?
- Is it an antipattern to use angular's $watch in a controller?
- Spring MongoRepository is updating or upserting instead of inserting
- Is it well-defined to use a pointer pointing to one-past-malloc?
- Java Lambdas : How it works in JVM & is it OOP? [closed]
- Is it common practice to turn on GC logging in production Java server?
- Does it make sense to use Google Web Toolkit (GWT) as a full-blown Java web framework?
- Multi-thread state visibility in Java: is there a way to turn the JVM into the worst case scenario?
- Where to use resolve() and relativize() method of java.nio.file.Path class?
- Is there any way to generate a UUID in Java that is identical to that of the one generated in C#?
- what's more efficient? to empty an object or create a new one?
- Is it ok to use DataSourceTransactionManager for ORM persistence instead of HibernateTransactionManager?
- How to call/bind a jquery datepicker to a label or div instead of an input field
- Is there a way to use \p{Punct} in a regex(java), but without the “(”,“)” characters?
- in ExtJS, is it better to call Model.save() or Store.Sync()?
- Is it currently possible to enable the mac's integrated graphics chip in a Java application?
- Is there a way to extract primary key(or ROWID) using NamedParameterJdbcTemplate and GeneratedKeyHolder?
- Is it better to use INNER JOIN or EXISTS to find belonging to several in m2m relation?
- How to create a java.sql.Blob object in Java SE 1.5.0 with a byte[] input?
- Are there any benefits to using Context.startForegroundService(Intent) instead of Context.startService(Intent) for...
- How to use hibernate.properties file instead of hibernate.cfg.xml
- What is the proper way to use a Logger in a Serializable Java class?
- Gson force use int instead of double
- Is it better using a guard clause or catching the exception? [closed]
- In SPSS, is it possible to export a dataset file to .CSV with the value names instead of the value numbers?
- Is there any reason to use vanilla Pure Data instead of Pd-extended?
- Is it possible to have a Map[String,Any] with the name and the values of named parameters in Scala?
- Is it not encouraged to use threads in web application?
- Entity Framework generates short instead of int
- In Java, is it possible to increase the JVM's available memory and/or kill other Java programs?
- When is it preferable to store data members as references instead of pointers?
- Does it make sense to use a framework for a simple java web app?
- Is it bad practice to use iframes? Can iframes be translated into images in the same way canvases can?
- Is It More Efficient to Put Raw Image Data in the Src Attr?
- Is it completely safe to use pattern of ReaderWriterLockSlim.EnterXXX() with consequent try-finally clause
- In Java is it possible to convert a BufferedImage to an IMG Data URI?
- Any reason to use byte/short etc.. in C#?
- When to use SQL natural join instead of join .. on?
- In C#, is there a way to generate an XDocument using the short prefix instead of the full namespace for each node?
- When to use an attribute (property) instead of an association/aggregation/composition when drawing a UML
- Is it considered better to use c-like initialization or constructor initialization in C++?
- how is it possible, 3 threads are in blocked state waiting same monitor, and there is no thread owned that monitor
- How do I get a Double out of a resultset instead of double?
- Is it not possible to supply a thread facory or name pattern to ForkJoinPool?
- How to get a custom type instead of Integer when using Collectors.summingInt?
- Is it possible to ignore the trailing return type feature of c++11 in favor of the function return type deduction...
- ServerSocket - Is it really necessary to close() it?
- In Java, how to use reflection to get a static method and execute it?
- Configure Windows to use 32-bit JRE instead of 64-bit JRE
- Is there any way to delete label or button from tkinter window and then add it back?
- Make Eclipse use src/test/resources instead of src/main/resources
- In Java, Is there a way to read a file when that file is locked by other thread?
- In Java, do methods that don't use static or class variables need to be synchronized?
- In Java, is there a more elegant way to remove duplicate strings from and ArrayList of Strings?
- Is it bad practice to use the system() function when library functions could be used instead? Why?
- In which cases it makes sense to use factory classes instead of static functions?
- Is it acceptable practice to use Singleton Objects to save state or share data between Activities?
- Is it good practice to use @BeanProperty in Scala instead of defining getter/setter functions?
- Is there a way to use weights with both layout width and height
- Can someone explain to me when it is useful to use MapMaker or WeakHashMaps?
- In Java, is an expression assignable to a declared variable iff. it can be passed as a parameter declared with the...
- Fast way to convert byte[] to short[] on Java Card
- Is it possible to open a .txt/.java file containing a class, and using reflection on it?
- How to use Jackson as JSON provider for JAX-RS-Client instead of Johnzon in TomEE 7?
- How to use varargs as the parameter of Constructor.getConstructor( ) in java
- Restricting ADFS 2.0 to use a specific OU instead of Domain level access
- In Java is it possible to dynamically create anonymous subclass instance given only instance of parent class?
- How to run tests by gradle instead of intelliJ with JUnit5 and SpringBoot2 in multi module project
- JDBC ResultSet object types mapping has no Byte or Short? Why Integer only?
- Internet Explorer wants to download the webpage of GuessNumber example application instead of displaying it
- How to use jQuery Deferred functionality instead of async.waterfall?
- Is it possible to add a JAR file of a library project and use its resources in another project?
- how to use java parallel stream instead of executorThreadsPool?
- Why is it not recommended to use HKCR registry root key in Inno Setup?
- casting between short,int,long,double,float in Java
- How to attach() and detach() instead of add() and remove() to save fragment view
- How to set parameter by name instead of its position in JDBC/JPA when calling stored procedure?
- Is it bad practice to make generic arrays, and what would be the alternative?
- Serialize Boolean to "1" and "0" instead of "true" and "false"
- Is it bad practice to use the same method for SAVE and UPDATE?
- Is it better to import specific packages or a whole tree with wildcards in java?
- Is it possible to change the colour of a line of text in Eclipse Java Editor based on it's content?
- is it always safe to use the first element of the array returned by split?
- Java: How to use byte literals greater than 0x7F
- How to update new plotline values instead of removing and adding new ones in highcharts
- Is there a way to get a look and feel of windows 8 metro on java desktop application?
- Is it a good idea to use string data type for dates in MySQL instead of using datetime data type?
- C++11 atomics: does it make sense, or is it even possible, to use them with memory mapped I/O?
- Why does the classpath default to the WEB-INF/classes/ instead of WEB-INF/ in JBoss 5.1?
- In Java, is it possible to cast to void (not Void)?
- Is it a good thing for a custom rest protocol to be binary based instead of text based like Http?
- JNI - Listener in C++/Java - is it possible to instantiate Java objects in c++ and use them as parameters
- Is it more efficient to set the size of a vector up front?
- Configure istio destination rule to use a fallback URL instead of 503
- Rxjava - when chaining observables how to get back other type of stream(return value) instead of current?
- Custom implementation of Thread in Java: Is it possible though JNI?
- Java, string instead of double after editing cell in TableModel
- In Java, is it possible to execute a method for a period of time and stop after it reaches the time limit?
Only authorized users can answer the Search term. Please sign in first, or register a free account.
short answer
yes, you are wrong. in most cases, it makes little difference in terms of space used.
it is not worth trying to optimize this ... unless you have clear evidence that optimization is needed. and if you do need to optimize memory usage of object fields in particular, you will probably need to take other (more effective) measures.
longer answer
the java virtual machine models stacks and object fields using offsets that are (in effect) multiples of a 32 bit primitive cell size. so when you declare a local variable or object field as (say) a
byte
, the variable / field will be stored in a 32 bit cell, just like anint
.there are two exceptions to this:
long
anddouble
values require 2 primitive 32-bit cellsso it might be worth optimizing use of
long
anddouble
... and large arrays of primitives. but in general no.in theory, a jit might be able to optimize this, but in practice i've never heard of a jit that does. one impediment is that the jit typically cannot run until after there instances of the class being compiled have been created. if the jit optimized the memory layout, you could have two (or more) "flavors" of object of the same class ... and that would present huge difficulties.
revisitation
looking at the benchmark results in @meriton's answer, it appears that using
short
andbyte
instead ofint
incurs a performance penalty for multiplication. indeed, if you consider the operations in isolation, the penalty is significant. (you shouldn't consider them in isolation ... but that's another topic.)i think the explanation is that jit is probably doing the multiplications using 32bit multiply instructions in each case. but in the
byte
andshort
case, it executes extra instructions to convert the intermediate 32 bit value to abyte
orshort
in each loop iteration. (in theory, that conversion could be done once at the end of the loop ... but i doubt that the optimizer would be able to figure that out.)anyway, this does point to another problem with switching to
short
andbyte
as an optimization. it could make performance worse ... in an algorithm that is arithmetic and compute intensive.